From 9aa0d96219c4959bcccfbc2cbfcde041f9646259 Mon Sep 17 00:00:00 2001 From: Mark Saniscalchi Date: Wed, 21 Oct 2015 06:43:36 -0700 Subject: [PATCH] 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)