Beispiel #1
0
class ErrorsTestV13(unittest.TestCase):
    """Unittest suite for Errors using v13."""

    SERVER = SERVER_V13
    VERSION = VERSION_V13
    TRIGGER_MSG1 = 'The developer token is invalid.'
    TRIGGER_CODE1 = 42
    TRIGGER_MSG2 = 'Login with this username/password failed.'
    TRIGGER_CODE2 = 9
    dummy_client = Client(path='..',
                          headers={
                              'email': 'xxxxxx',
                              'password': '******',
                              'useragent': 'ErrorsTest',
                              'developerToken': 'xxxxxx++USD'
                          })
    dummy_client.debug = False

    def setUp(self):
        """Prepare unittest."""
        print self.id()
        self.__class__.dummy_client.use_mcc = True

    def tearDown(self):
        """Finalize unittest."""
        self.__class__.dummy_client.use_mcc = False

    def testApiError(self):
        """Tests whether we can catch an Errors.ApiError exception."""
        try:
            self.__class__.dummy_client.GetAccountService(
                self.__class__.SERVER, self.__class__.VERSION,
                HTTP_PROXY).GetAccountInfo()
        except ApiError, e:
            try:
                self.assertEqual(e.message, self.__class__.TRIGGER_MSG1)
                self.assertEqual(e.code, self.__class__.TRIGGER_CODE1)
            except:
                self.assertEqual(e.message, self.__class__.TRIGGER_MSG2)
                self.assertEqual(e.code, self.__class__.TRIGGER_CODE2)
Tags: InfoService.get
"""

__author__ = '[email protected] (Stan Grinberg)'

import datetime
import sys
sys.path.append('../..')

# Import appropriate classes from the client library.
from aw_api.Client import Client


# Initialize client object.
client = Client(path='../..')

# Initialize appropriate service.
info_service = client.GetInfoService(
    'https://adwords-sandbox.google.com', 'v200909')

# Construct info selector object and retrieve usage info.
today = datetime.datetime.today()
service_name = 'AdGroupService'
method_name = 'mutate'
operator = 'SET'
selector = {
    'dateRange': {
        'min': '%s%s01' % (today.year, today.month),
        'max': '%s%s01' % (today.year, today.month)
    },
Beispiel #3
0
"""This example gets all geo location information for a given list of
addresses.

Tags: GeoLocationService.get
"""

__author__ = '[email protected] (Stan Grinberg)'

import sys
sys.path.append('../..')

# Import appropriate classes from the client library.
from aw_api.Client import Client

# Initialize client object.
client = Client(path='../..')

# Initialize appropriate service.
geo_location_service = client.GetGeoLocationService(
    'https://adwords-sandbox.google.com', 'v201003')

# Construct selector and get all geo location info.
selector = {
    'addresses': [{
        'streetAddress': '1600 Amphitheatre Parkway',
        'cityName': 'Mountain View',
        'provinceCode': 'US-CA',
        'provinceName': 'California',
        'postalCode': '94043',
        'countryCode': 'US'
    }, {
Beispiel #4
0
Tags: BulkMutateJobService.mutate
"""

__author__ = '[email protected] (Stan Grinberg)'

import os
import sys

sys.path.append('../..')

# Import appropriate classes from the client library.
from aw_api import Utils
from aw_api.Client import Client

# Initialize client object.
client = Client(path='../..')

# Initialize appropriate service.
bulk_mutate_job_service = client.GetBulkMutateJobService(
    'https://adwords-sandbox.google.com', 'v201003')

campaign_id = 'INSERT_CAMPAIGN_ID_HERE'
ad_group_id = 'INSERT_AD_GROUP_ID_HERE'

# Construct part for adding ads and add it to a job.
ads = {
    'scopingEntityId': {
        'type': 'CAMPAIGN_ID',
        'value': campaign_id,
    },
    'operations': [{
Beispiel #5
0
range.

Tags: InfoService.get
"""

__author__ = '[email protected] (Stan Grinberg)'

import datetime
import sys
sys.path.append('../..')

# Import appropriate classes from the client library.
from aw_api.Client import Client

# Initialize client object.
client = Client(path='../..')

# Initialize appropriate service.
info_service = client.GetInfoService('https://adwords-sandbox.google.com',
                                     'v200909')

# Construct info selector object and retrieve usage info.
today = datetime.datetime.today()
selector = {
    'dateRange': {
        'min': '%s%s01' % (today.year, today.month),
        'max': '%s%s%s' % (today.year, today.month, today.day)
    },
    'apiUsageType': 'UNIT_COUNT'
}
info = info_service.Get(selector)[0]
"""This example gets all images. To upload an image, run upload_image.py.

Tags: MediaService.get
"""

__author__ = '[email protected] (Stan Grinberg)'

import sys
sys.path.append('../..')

# Import appropriate classes from the client library.
from aw_api import Utils
from aw_api.Client import Client

# Initialize client object.
client = Client(path='../..')

# Initialize appropriate service.
media_service = client.GetMediaService('https://adwords-sandbox.google.com',
                                       'v201003')

# Construct selector and get all images.
selector = {'mediaType': 'IMAGE'}
images = media_service.Get(selector)[0]

# Display results.
if 'media' in images:
    for image in images['media']:
        dimensions = Utils.GetMap(image['dimensions'])
        print(
            'Image with id \'%s\', dimensions \'%sx%s\', and MIME type \'%s\' '
Beispiel #7
0
"""This example adds geo, language, and network targets to a given campaign. To
get campaigns, run get_all_campaigns.py.

Tags: CampaignTargetService.mutate
"""

__author__ = '[email protected] (Stan Grinberg)'

import sys
sys.path.append('../..')

# Import appropriate classes from the client library.
from aw_api.Client import Client

# Initialize client object.
client = Client(path='../..')

# Initialize appropriate service.
campaign_target_service = client.GetCampaignTargetService(
    'https://adwords-sandbox.google.com', 'v200909')

campaign_id = 'INSERT_CAMPAIGN_ID_HERE'

# Construct operations and set campaign targets.
operations = [{
    'operator': 'SET',
    'operand': {
        'type':
        'GeoTargetList',
        'campaignId':
        campaign_id,
Beispiel #8
0
"""This example gets report fields.

Tags: ReportDefinitionService.getReportFields
"""

__author__ = '[email protected] (Stan Grinberg)'

import sys
sys.path.append('../..')

# Import appropriate classes from the client library.
from aw_api.Client import Client


# Initialize client object.
client = Client(path='../..')

# Initialize appropriate service.
report_definition_service = client.GetReportDefinitionService(
    'https://adwords-sandbox.google.com', 'v201003')

report_type = 'INSERT_REPORT_TYPE_HERE'

# Get report fields.
fields = report_definition_service.GetReportFields(report_type)

# Display results.
print 'Report type \'%s\' contains the following fields:' % report_type
for field in fields:
  print ' - %s (%s)' % (field['fieldName'], field['fieldType'])
  if field['enumValues']:
Beispiel #9
0
"""This example adds a campaign ad extension to a given campaign. To get
campaigns, run get_all_campaigns.py.

Tags: GeoLocationService.get, CampaignAdExtensionService.mutate
"""

__author__ = '[email protected] (Stan Grinberg)'

import sys
sys.path.append('../..')

# Import appropriate classes from the client library.
from aw_api.Client import Client

# Initialize client object.
client = Client(path='../..')

# Initialize appropriate service.
geo_location_service = client.GetGeoLocationService(
    'https://adwords-sandbox.google.com', 'v200909')
campaign_ad_extension_service = client.GetCampaignAdExtensionService(
    'https://adwords-sandbox.google.com', 'v200909')

campaign_id = 'INSERT_CAMPAIGN_ID_HERE'

# Construct selector and get geo location info for given addresses.
selector = {
    'addresses': [{
        'streetAddress': '1600 Amphitheatre Parkway',
        'cityName': 'Mountain View',
        'provinceCode': 'US-CA',
add_campaign.py.

Tags: CampaignService.get
"""

__author__ = '[email protected] (Stan Grinberg)'

import sys
sys.path.append('../..')

# Import appropriate classes from the client library.
from aw_api.Client import Client


# Initialize client object.
client = Client(path='../..')

# Initialize appropriate service.
campaign_service = client.GetCampaignService(
    'https://adwords-sandbox.google.com', 'v201003')

# Construct selector and get all paused campaigns.
selector = {
    'campaignStatuses': ['PAUSED']
}
campaigns = campaign_service.Get(selector)[0]

# Display results.
if 'entries' in campaigns:
  for campaign in campaigns['entries']:
    print ('Campaign with id \'%s\', name \'%s\', and status \'%s\' was found.'
campaigns, run get_all_campaigns.py.

Tags: GeoLocationService.get, AdExtensionOverrideService.mutate
"""

__author__ = '[email protected] (Stan Grinberg)'

import sys
sys.path.append('../..')

# Import appropriate classes from the client library.
from aw_api.Client import Client


# Initialize client object.
client = Client(path='../..')

# Initialize appropriate service.
geo_location_service = client.GetGeoLocationService(
    'https://adwords-sandbox.google.com', 'v201003')
ad_extension_override_service = client.GetAdExtensionOverrideService(
    'https://adwords-sandbox.google.com', 'v201003')

ad_id = 'INSERT_AD_GROUP_AD_ID_HERE'
ad_extension_id = 'INSERT_AD_EXTENSION_ID_HERE'

# Construct selector and get geo location info for a given address.
selector = {
    'addresses': [
        {
            'streetAddress': '1600 Amphitheatre Parkway',
__author__ = '[email protected] (Stan Grinberg)'

# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import sys
sys.path.append('../..')

# Import appropriate constants and classes from the client library.
from aw_api.Client import Client


# Initialize Client object. The "path" parameter should point to the location of
# pickles, which get generated after execution of "aw_api_config.py" script. The
# same location is used for the "logs/" directory, if logging is enabled.
client = Client(path='../..')

# Temporarily disable debugging. If enabled, the debugging data will be send to
# STDOUT.
client.debug = False

# Fetch existing campaigns.
print 'Fetching existing campaigns using v200909...'
selector = {'ids': []}
campaigns = client.GetCampaignService(
    'https://adwords-sandbox.google.com', 'v200909').Get(selector)
campaign_ids = []
for campaign in campaigns[0]['entries']:
  # We only care about active campaigns.
  if campaign['status'] not in ('DELETED', 'PAUSED'):
    campaign_ids.append(campaign['id'])
Beispiel #13
0
Tags: BidLandscapeService.getBidLandscape
"""

__author__ = '[email protected] (Stan Grinberg)'

import os
import sys

sys.path.append(os.path.join('..', '..'))

# Import appropriate classes from the client library.
from aw_api.Client import Client

# Initialize client object.
client = Client(path=os.path.join('..', '..'))

# Initialize appropriate service.
bid_landscape_service = client.GetBidLandscapeService(
    'https://adwords-sandbox.google.com', 'v201003')

ad_group_id = 'INSERT_AD_GROUP_ID_HERE'
criterion_id = 'INSERT_CRITERION_ID_HERE'

# Construct bid landscape selector object and retrieve bid landscape.
selector = {
    'type': 'CriterionBidLandscapeSelector',
    'idFilters': [{
        'adGroupId': ad_group_id,
        'criterionId': criterion_id
    }]
"""This example shows how to check for conversion optimizer eligibility.

Tags: CampaignService.mutate
"""

__author__ = '[email protected] (Stan Grinberg)'

import sys
sys.path.append('../..')

# Import appropriate classes from the client library.
from aw_api.Client import Client
from aw_api.Errors import RequestError

# Initialize client object.
client = Client(path='../..')

# Initialize appropriate service with validate only flag enabled.
client.validate_only = True
campaign_service = client.GetCampaignService(
    'https://adwords-sandbox.google.com', 'v200909')

campaign_id = 'INSERT_CAMPAIGN_ID_HERE'

# Construct operations for setting bidding transition on a campaign.
try:
    operations = [{
        'operator': 'SET',
        'biddingTransition': {
            'targetBiddingStrategy': {
                'type': 'ConversionOptimizer',
Tags: CampaignService.mutate
"""

__author__ = '[email protected] (Stan Grinberg)'

import sys
sys.path.append('../..')

# Import appropriate classes from the client library.
from aw_api.Client import Client
from aw_api.Errors import RequestError


# Initialize client object.
client = Client(path='../..')

# Initialize appropriate service with validate only flag enabled.
client.validate_only = True
campaign_service = client.GetCampaignService(
    'https://adwords-sandbox.google.com', 'v200909')

campaign_id = 'INSERT_CAMPAIGN_ID_HERE'

# Construct operations for setting bidding transition on a campaign.
try:
  operations = [{
      'operator': 'SET',
      'biddingTransition': {
          'targetBiddingStrategy': {
              'type': 'ConversionOptimizer',
Beispiel #16
0
"""This example adds ad group criteria to an ad group. To get ad groups, run
get_all_ad_groups.py.

Tags: AdGroupCriterionService.mutate
"""

__author__ = '[email protected] (Stan Grinberg)'

import sys
sys.path.append('../..')

# Import appropriate classes from the client library.
from aw_api.Client import Client

# Initialize client object.
client = Client(path='../..')

# Initialize appropriate service.
ad_group_criterion_service = client.GetAdGroupCriterionService(
    'https://adwords-sandbox.google.com', 'v200909')

ad_group_id = 'INSERT_AD_GROUP_ID_HERE'

# Construct keyword ad group criterion object.
keyword = {
    'type': 'BiddableAdGroupCriterion',
    'adGroupId': ad_group_id,
    'criterion': {
        'type': 'Keyword',
        'matchType': 'BROAD',
        'text': 'mars'
# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import sys

sys.path.append("../..")

# Import appropriate constants and classes from the client library.
from aw_api import SOAPPY
from aw_api.Client import Client


# Initialize Client object. The "path" parameter should point to the location of
# pickles, which get generated after execution of "aw_api_config.py" script. The
# same location is used for the "logs/" directory, if logging is enabled. The
# "soap_lib" parameter can be used to specify which SOAP toolkit to use.
client = Client(path="../..", soap_lib=SOAPPY)
# OR another way of specifying authentication data is through "headers"
# parameter, which takes precedence over loading from a pickle. The "path" is
# optional here and is specified to let client library know where to place logs.
# client = Client(headers={
#    'email': '*****@*****.**',
#    'password': '******',
#    'userAgent': 'My Test',
#    'developerToken': '[email protected]++USD'}, path='..')

# Temporarily disable debugging. If enabled, the debugging data will be send to
# STDOUT.
client.debug = False

# Force following API requests to go against MCC account. This can be changed
# at any time by setting it back to False.
"""This example retrieves urls that have content keywords related to a given
website.

Tags: TargetingIdeaService.get
"""

__author__ = '[email protected] (Stan Grinberg)'

import sys
sys.path.append('../..')

# Import appropriate classes from the client library.
from aw_api.Client import Client

# Initialize client object.
client = Client(path='../..')

# Initialize appropriate service.
targeting_idea_service = client.GetTargetingIdeaService(
    'https://adwords-sandbox.google.com', 'v201003')

# Construct info selector object and retrieve usage info.
url = 'http://mars.google.com'
selector = {
    'searchParameters': [{
        'type': 'RelatedToUrlSearchParameter',
        'urls': [url],
        'includeSubUrls': 'False'
    }],
    'ideaType':
    'PLACEMENT',
Beispiel #19
0
"""This example gets all ad extension overrides in a given campaign. To add an
ad extension override, run add_ad_extension_override.py.

Tags: AdExtensionOverrideService.get
"""

__author__ = '[email protected] (Stan Grinberg)'

import sys
sys.path.append('../..')

# Import appropriate classes from the client library.
from aw_api.Client import Client

# Initialize client object.
client = Client(path='../..')

# Initialize appropriate service.
ad_extension_override_service = client.GetAdExtensionOverrideService(
    'https://adwords-sandbox.google.com', 'v200909')

campaign_id = 'INSERT_CAMPAIGN_ID_HERE'

# Construct selector and get all campaigns.
selector = {'campaignIds': [campaign_id]}
ad_extensions = ad_extension_override_service.Get(selector)[0]

# Display results.
if 'entries' in ad_extensions:
    for ad_extension in ad_extensions['entries']:
        print('Ad extension with id \'%s\' and status \'%s\' was found.' %
Beispiel #20
0
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

"""Settings and configuration for the unit tests."""

__author__ = '[email protected] (Stan Grinberg)'

import sys
sys.path.append('..')

from aw_api import SOAPPY
from aw_api import ZSI
from aw_api.Client import Client


HTTP_PROXY = None
SERVER_V13 = 'https://sandbox.google.com'
SERVER_V200909 = 'https://adwords-sandbox.google.com'
SERVER_V201003 = 'https://adwords-sandbox.google.com'
VERSION_V13 = 'v13'
VERSION_V200909 = 'v200909'
VERSION_V201003 = 'v201003'
client = Client(path='..', config={'use_strict': 'y'})
client.soap_lib = ZSI
Beispiel #21
0
# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import sys
sys.path.append('../..')

# Import appropriate constants and classes from the client library.
from aw_api import MIN_API_VERSION
from aw_api import SOAPPY
from aw_api.Client import Client


# Initialize Client object. The "path" parameter should point to the location of
# pickles, which get generated after execution of "aw_api_config.py" script. The
# same location is used for the "logs/" directory, if logging is enabled.
client = Client(path='../..')

# Temporarily disable debugging. If enabled, the debugging data will be send to
# STDOUT.
client.debug = False

# 1. Schedule report job by calling "scheduleReportJob" method directly,
# bypassing library's validation logic. This way of scheduling report only works
# with SOAPpy toolkit.
#
# Construct report job.
if client.soap_lib == SOAPPY:
  job = ("""<aggregationTypes>%s</aggregationTypes>
<endDay>%s</endDay>
<name>%s</name>
<selectedColumns>%s</selectedColumns>
Beispiel #22
0
Tags: AdGroupAdService.mutate
"""

__author__ = '[email protected] (Stan Grinberg)'

import base64
import sys
sys.path.append('../..')

# Import appropriate classes from the client library.
from aw_api import SOAPPY
from aw_api import Utils
from aw_api.Client import Client

# Initialize client object.
client = Client(path='../..')

# Initialize appropriate service.
ad_group_ad_service = client.GetAdGroupAdService(
    'https://adwords-sandbox.google.com', 'v201003')

ad_group_id = 'INSERT_AD_GROUP_ID_HERE'
video_media_id = 'INSERT_VIDEO_MEDIA_ID'
image_data = Utils.ReadFile('INSERT_IMAGE_PATH_HERE')
if client.soap_lib == SOAPPY:
    image_data = base64.encodestring(image_data)

# Construct operations and add ads.
operations = [{
    'operator': 'ADD',
    'operand': {
"""This example creates new negative campaign criterion. To create campaign, run
add_campaign.py.

Tags: CampaignCriterionService.mutate
"""

__author__ = '[email protected] (Stan Grinberg)'

import sys
sys.path.append('../..')

# Import appropriate classes from the client library.
from aw_api.Client import Client

# Initialize client object.
client = Client(path='../..')

# Initialize appropriate service.
campaign_criterion_service = client.GetCampaignCriterionService(
    'https://adwords-sandbox.google.com', 'v201003')

# Construct campaign criterion object and add negative campaign criterion.
campaign_id = 'INSERT_CAMPAIGN_ID_HERE'
operations = [{
    'operator': 'ADD',
    'operand': {
        'type': 'NegativeCampaignCriterion',
        'campaignId': campaign_id,
        'criterion': {
            'type': 'Keyword',
            'matchType': 'BROAD',
# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import sys
sys.path.append('../..')

# Import appropriate constants and classes from the client library.
from aw_api import LIB_HOME
from aw_api import MIN_API_VERSION
from aw_api import Utils
from aw_api.Client import Client
from aw_api.Errors import ApiError

# Initialize Client object. The "path" parameter should point to the location of
# pickles, which get generated after execution of "aw_api_config.py" script. The
# same location is used for the "logs/" directory, if logging is enabled.
client = Client(path='../..')

# Temporarily disable debugging. If enabled, the debugging data will be send to
# STDOUT.
client.debug = False

# Construct SOAP message by loading XML from existing data file.
soap_message = Utils.ReadFile(
    os.path.join(LIB_HOME, 'data', 'request_getaccountinfo.xml'))
url = '/api/adwords/%s/AccountService' % MIN_API_VERSION
http_proxy = None

try:
    response = client.CallRawMethod(soap_message, url, http_proxy)[0]

    # Display results.
Beispiel #25
0
"""Script to clear current client account in Sandbox of all its data.

The Sandbox is cleared by setting status of all campaigns to "Deleted". This is
a workaround for a code 17, "This account already has the maximum number of
Campaigns permitted." error."""

__author__ = '[email protected] (Stan Grinberg)'

import sys
sys.path.append('..')

from aw_api.Client import Client

SERVER = 'https://adwords-sandbox.google.com'
VERSION = 'v200909'
client = Client(path='..')
client.debug = False
client.use_mcc = False

selector = {'campaignStatuses': ['ACTIVE', 'PAUSED']}
campaign_service = client.GetCampaignService(SERVER, VERSION)
campaigns = campaign_service.Get(selector)[0]

if 'entries' in campaigns:
    campaigns = campaigns['entries']
    operations = []
    for campaign in campaigns:
        print '%s: status=\'%s\'' % (campaign['name'], campaign['status']),
        operations.append({
            'operator': 'SET',
            'operand': {