Exemple #1
0
 def testSaveCreativeFieldValue(self):
     """Test whether we can save a creative field value"""
     if self.__class__.creative_field_id == '0':
         self.testSaveCreativeField()
     creative_field_value = {
         'name': 'FieldValue #%s' % Utils.GetUniqueName(),
         'creativeFieldId': self.__class__.creative_field_id,
         'id': '-1'
     }
     creative_field_value = self.__class__.service.SaveCreativeFieldValue(
         creative_field_value)
     self.__class__.creative_field_value_id = creative_field_value[0]['id']
     self.assert_(isinstance(creative_field_value, tuple))
def main():
    try:
        Utils.GetAuthToken(login_email, password, AUTH_TOKEN_SERVICE, LIB_SIG,
                           None)
    except AuthTokenError, e:
        if str(e).find('InvalidSecondFactor') != -1:
            print """The user has enabled two factor authentication in this
  account. Have the user generate an application-specific password to make
  calls against the AdWords API. See
  http://adwordsapi.blogspot.com/2011/02/authentication-changes-with-2-step.html
  for more details."""
        else:
            raise e
def main(client, order_id):
    # Initialize appropriate service.
    line_item_service = client.GetService('LineItemService', version='v201405')

    # Create statement object to only select line items with even delivery rates.
    values = [{
        'key': 'deliveryRateType',
        'value': {
            'xsi_type': 'TextValue',
            'value': 'EVENLY'
        }
    }, {
        'key': 'orderId',
        'value': {
            'xsi_type': 'NumberValue',
            'value': order_id
        }
    }]

    query = 'WHERE deliveryRateType = :deliveryRateType and orderId = :orderId'
    statement = DfpUtils.FilterStatement(query, values, 500)

    # Get line items by statement.
    response = line_item_service.GetLineItemsByStatement(
        statement.ToStatement())[0]

    line_items = response.get('results')

    if line_items:
        # Update each local line item by changing its delivery rate type.
        updated_line_items = []
        for line_item in line_items:
            if not Utils.BoolTypeConvert(line_item['isArchived']):
                line_item['deliveryRateType'] = 'AS_FAST_AS_POSSIBLE'
                updated_line_items.append(line_item)

        # Update line items remotely.
        line_items = line_item_service.UpdateLineItems(updated_line_items)

        # Display results.
        if line_items:
            for line_item in line_items:
                print(
                    'Line item with id \'%s\', belonging to order id \'%s\', named '
                    '\'%s\', and delivery rate \'%s\' was updated.' %
                    (line_item['id'], line_item['orderId'], line_item['name'],
                     line_item['deliveryRateType']))
        else:
            print 'No line items were updated.'
    else:
        print 'No line items found to update.'
def _RestoreListTypesForResponse(response, xsi_type, service_type_map):
    """Restores list types for an individual response object.

  Args:
    response: obj An individual object returned by the webservice. May be a
              dictionary, list, or string depending on what it represents.
    xsi_type: str The WSDL-defined type of this response.
    service_type_map: dict Information on WSDL-defined types in one service.

  Returns:
    obj The response in its proper format. May be a dictionary, list, or string
    depending on what was input. Not guaranteed to output the same data type
    that was input - may output a list instead.
  """
    if isinstance(response, dict):
        if not response: return response
        for param, param_type in Utils.GenParamOrder(service_type_map,
                                                     xsi_type):
            if not param in response or Utils.IsXsdOrSoapenc(param_type):
                continue
            value = response[param]
            if (service_type_map[param_type]['soap_type'] == 'array'
                    and not isinstance(response[param], list)):
                value = [value]
            response[param] = _RestoreListTypesForResponse(
                value, param_type, service_type_map)
        return response
    elif isinstance(response, list):
        lst = []
        for item in response:
            if item is None: continue
            lst.append(
                _RestoreListTypesForResponse(
                    item, service_type_map[xsi_type]['base_type'],
                    service_type_map))
        return lst
    else:
        return response
Exemple #5
0
def main(client):
  # Initialize appropriate service.
  company_service = client.GetService('CompanyService', version='v201206')

  # Create company objects.
  companies = [
      {
          'name': 'Advertiser #%s' % Utils.GetUniqueName(),
          'type': 'ADVERTISER'
      },
      {
          'name': 'Agency #%s' % Utils.GetUniqueName(),
          'type': 'AGENCY'
      }
  ]

  # Add companies.
  companies = company_service.CreateCompanies(companies)

  # Display results.
  for company in companies:
    print ('Company with ID \'%s\', name \'%s\', and type \'%s\' was created.'
           % (company['id'], company['name'], company['type']))
 def testAddRemarketingUserList(self):
     """Test whether we can add a remarketing user list."""
     operations = [{
         'operator': 'ADD',
         'operand': {
             'xsi_type':
             'RemarketingUserList',
             'name':
             'Mars cruise customers #%s' % Utils.GetUniqueName(),
             'description':
             'A list of mars cruise customers in the last '
             'year.',
             'membershipLifeSpan':
             '365',
             'conversionTypes': [{
                 'name':
                 ('Mars cruise customers #%s' % Utils.GetUniqueName())
             }]
         }
     }]
     user_lists = self.__class__.service.Mutate(operations)
     self.__class__.user_list = user_lists[0]['value'][0]
     self.assert_(isinstance(user_lists, tuple))
 def testSaveSpotlightConfiguration(self):
     """Test whether we can save a spotlight configuration."""
     spotlight_configuration = {
         'name': 'SpotlightConfiguration #%s' % Utils.GetUniqueName(),
         'id': self.__class__.advertiser_id,
         'firstDayOfWeek': '1',
         'motifEventsDays': '30',
         'clickDays': '30',
         'impressionDays': '30'
     }
     spotlight_configuration = self.__class__.service.SaveSpotlightConfiguration(
         spotlight_configuration)
     self.__class__.configuration_id = spotlight_configuration[0]['id']
     self.assert_(isinstance(spotlight_configuration, tuple))
 def testCreateAdUnit(self):
     """Test whether we can create an ad unit."""
     ad_unit = {
         'name': 'Ad_Unit_%s' % Utils.GetUniqueName(),
         'parentId': self.__class__.root_ad_unit_id,
         'sizes': [{
             'width': '300',
             'height': '250'
         }],
         'description': 'Ad unit description.',
         'targetWindow': 'BLANK'
     }
     self.assert_(
         isinstance(self.__class__.service.CreateAdUnit(ad_unit), tuple))
    def sign(self, soap_writer):
        """Sign signature handler.

    Args:
      soap_writer: SoapWriter instance.
    """
        keys = []
        for key in self.__headers:
            keys.append((key, self.__headers[key]))
        keys = tuple(keys)

        header = soap_writer._header
        body = soap_writer.body
        # Set RequestHeader element, if appropriate.
        if 'ns_target' in self.__config:
            name_space, target = self.__config['ns_target']
            header = header.createAppendElement('', target)
            header.setNamespaceAttribute('', name_space)

            # Explicitly set namespace at the request method's level. For services
            # with multiple namespaces, this has to be done prior to checking where
            # RequestHeader elements point.
            if body._getElements():
                body._getElements()[0].setAttributeNS('', 'xmlns:ns1',
                                                      name_space)

            # Make sure that the namespace for RequestHeader elements is pointing
            # at default namespace, if present.
            if (self.__group and self.__group
                    not in Utils.GetPathFromUrl(name_space).split('/')):
                parts = name_space.split('/')
                parts[-2] = self.__group
                name_space = '/'.join(parts)
        else:
            name_space = ''
        for key, value in keys:
            if value:
                if isinstance(value, dict):
                    if 'auth_type' not in self.__config:
                        self.__config['auth_type'] = ''
                    obj = header.createAppendElement(name_space, key)
                    obj.node.setAttribute('xsi:type',
                                          self.__config['auth_type'])
                    for sub_key in value:
                        obj.createAppendElement(name_space,
                                                sub_key).createAppendTextNode(
                                                    value[sub_key])
                else:
                    header.createAppendElement(name_space,
                                               key).createAppendTextNode(value)
Exemple #10
0
def SoappySanityCheck(soappy_service, obj, ns, obj_type, max_occurs='1'):
    """Validates any given object against its WSDL definition.

  This method considers None and the empty string to be a valid representation
  of any type.

  Args:
    soappy_service: SOAPpy.WSDL.Proxy An object encapsulating a SOAP service.
    obj: Object to be validated. Depending on the WSDL-defined type this object
         represents, the data type will vary. It should always be either a
         dictionary, list, or string no matter what WSDL-defined type it is.
    ns: string The namespace the given type belongs to.
    obj_type: A string specifying the type name defined in the WSDL.
    max_occurs: string The maxOccurs attribute for this object.

  Raises:
    ValidationError: The given type has no definition in the WSDL or the given
                     object is not a valid representation of the type defined in
                     the WSDL.
  """
    if obj in (None, ''):
        return
    elif Utils.IsBaseSoapType(obj_type):
        try:
            ValidateTypes(((obj, (str, unicode)), ))
        except ValidationError:
            raise ValidationError(
                'Objects of type \'%s\' should be a string but '
                'value \'%s\' is a \'%s\' instead.' %
                (obj_type, obj, type(obj)))
    else:
        try:
            soap_type = soappy_service.wsdl.types[ns].types[obj_type].tag
            if soap_type == 'simpleType':
                _SoappySanityCheckSimpleType(obj, obj_type)
            elif soap_type == 'complexType':
                if (SoappyUtils.IsAnArrayType(obj_type, ns, soappy_service)
                        or not max_occurs.isdigit() or int(max_occurs) > 1):
                    _SoappySanityCheckArray(soappy_service, obj, ns, obj_type)
                else:
                    _SoappySanityCheckComplexType(soappy_service, obj, ns,
                                                  obj_type)
            else:
                raise ValidationError(
                    'Unrecognized type definition tag in WSDL: \'%s\'' %
                    soap_type)
        except KeyError:
            raise ValidationError(
                'This type is not defined in the WSDL: \'%s\'' % obj_type)
  def DownloadMCCReport(self, report_definition_id, file_path=None,
                        return_micros=False, tries=50, sleep=30):
    """Blocking call to download a MCC report.

    This method will try to successfully download the report to the specified
    file_path, throwing an AdWordsApiError.  If file_path is None or not
    provided, will return as a string the downloaded report.

    Args:
      report_definition_id: str Id of the report definition to download.
      file_path: str File path to download to. Optional, returns string if None.
      return_micros: bool Whether to return currency in micros.
      tries: int Optional number of times to retry.
      sleep: int Optional number of seconds to sleep between retries.

    Returns:
      str Report data or a tuple of filename and bytes written if file_path is
      not None.

    Raises:
      AdWordsApiError: When we encounter a server error
    """
    response = self.GetMCCReportStatus(report_definition_id, return_micros,
                                       'new')
    while response['httpStatus'] != 301 and tries > 0:
      if response['httpStatus'] != 200:
        msg = []
        if 'state' in response: msg.append(response['state'])
        if 'failureReason' in response: msg.append(response['failureReason'])
        raise AdWordsApiError({
            'faultcode': '500',
            'faultstring': ' '.join(msg)})
      # Otherwise, it should be status == 200 which means try again later.
      if Utils.BoolTypeConvert(self._config['debug']):
        print 'Sleeping with %i tries left' % tries
      tries -= 1
      time.sleep(sleep)
      response = self.GetMCCReportStatus(report_definition_id, return_micros,
                                         response['queryToken'])
    if tries <= 0:
      raise AdWordsApiError({'faultstring': 'No more retries left.'})
    # On success, get the download URL from the Location header
    url = None
    if 'Location' in response['headers']:
      url = response['headers']['Location']
    else:
      url = response['headers']['location']
    headers = self.__GenerateHeaders(return_micros)
    return self.__DownloadFile(url, headers, file_path)
def DownloadReport(report_job_id, export_format, service):
    """Download and return report data.

  Args:
    report_job_id: str ID of the report job.
    export_format: str Export format for the report file.
    service: GenericDfpService A service pointing to the ReportService.

  Returns:
    str Report data or empty string if report failed.
  """
    SanityCheck.ValidateTypes(((report_job_id, (str, unicode)), ))

    # Wait for report to complete.
    status = service.GetReportJob(report_job_id)[0]['reportJobStatus']
    while status != 'COMPLETED' and status != 'FAILED':
        if Utils.BoolTypeConvert(service._config['debug']):
            print 'Report job status: %s' % status
        time.sleep(30)
        status = service.GetReportJob(report_job_id)[0]['reportJobStatus']

    if status == 'FAILED':
        if Utils.BoolTypeConvert(service._config['debug']):
            print 'Report process failed'
        return ''
    else:
        if Utils.BoolTypeConvert(service._config['debug']):
            print 'Report has completed successfully'

    # Get report download URL.
    report_url = service.GetReportDownloadURL(report_job_id, export_format)[0]

    # Download report.
    data = urllib.urlopen(report_url).read()
    data = gzip.GzipFile(fileobj=StringIO.StringIO(data)).read()
    return data
def CreateTestCreative(client, server, version, advertiser_id):
    """Create a test creative.

  Args:
    client: DfpClient used for service creation.
    server: str the API server.
    version: str the API version.
    advertiser_id: str the company ID for the creative's advertiser.

  Returns:
    The ID of the creative.
  """
    creative_service = client.GetService('CreativeService', server, version)

    # Create creative object.
    image_data = Utils.ReadFile(
        os.path.join(__file__[:__file__.rfind('/')], '..', 'data',
                     'medium_rectangle.jpg'))
    image_data = base64.encodestring(image_data)

    creative = {
        'type': 'ImageCreative',
        'name': 'Image Creative #%s' % Utils.GetUniqueName(),
        'advertiserId': advertiser_id,
        'destinationUrl': 'http://google.com',
        'imageName': 'image.jpg',
        'imageByteArray': image_data,
        'size': {
            'width': '300',
            'height': '250'
        }
    }

    # Add creatives.
    creatives = creative_service.CreateCreatives([creative])
    return creatives[0]['id']
 def testAddConversion(self):
     """Test whether we can add a conversion."""
     operations = [{
         'operator': 'ADD',
         'operand': {
             'xsi_type': 'AdWordsConversionTracker',
             'name': 'Mars cruise customers #%s' % Utils.GetUniqueName(),
             'category': 'DEFAULT',
             'markupLanguage': 'HTML',
             'httpProtocol': 'HTTP',
             'textFormat': 'HIDDEN'
         }
     }]
     self.assert_(
         isinstance(self.__class__.service.Mutate(operations), tuple))
 def testSaveSpotlightActivityGroup(self):
     """Test whether we can save a spotlight activity group."""
     if self.__class__.configuration_id == '0':
         self.testSaveSpotlightConfiguration()
     configuration_id = self.__class__.configuration_id
     spotlight_activity_group = {
         'name': 'SpotlightActivityGroup #%s' % Utils.GetUniqueName(),
         'groupType': '1',  # Counter Activity
         'spotlightConfigurationId': configuration_id
     }
     spotlight_activity_group = \
         self.__class__.service.SaveSpotlightActivityGroup(
             spotlight_activity_group)
     self.__class__.activity_group_id = spotlight_activity_group[0]['id']
     self.assert_(isinstance(spotlight_activity_group, tuple))
Exemple #16
0
def main(client, image_filename):
    # Initialize appropriate service.
    media_service = client.GetMediaService(version='v201406')

    image_data = Utils.ReadFile(image_filename)
    image_data = base64.encodestring(image_data)

    # Construct media and upload image.
    media = [{'xsi_type': 'Image', 'data': image_data, 'type': 'IMAGE'}]
    media = media_service.Upload(media)[0]

    # Display results.
    if media:
        dimensions = Utils.GetDictFromMap(media['dimensions'])
        print(
            'Image with id \'%s\', dimensions \'%sx%s\', and MimeType \'%s\' was'
            ' uploaded.' % (media['mediaId'], dimensions['FULL']['height'],
                            dimensions['FULL']['width'], media['mimeType']))
    else:
        print 'No images were uploaded.'

    print
    print('Usage: %s units, %s operations' %
          (client.GetUnits(), client.GetOperations()))
Exemple #17
0
 def testAssignCreativesToPlacements(self):
   """Test whether we can assign creatives to placements."""
   if self.__class__.creative_id == '0':
     self.testSaveCreative()
   creative_id = self.__class__.creative_id
   placement_id = self.__class__.placement_id
   creative_placement_assignments = [{
       'adName': 'Ad #%s' % Utils.GetUniqueName(),
       'creativeId': creative_id,
       'placementId': placement_id,
       'placementIds': [placement_id, placement_id]
   }]
   creative_placement_assignments = \
       self.__class__.service.AssignCreativesToPlacements(
           creative_placement_assignments)
   self.assert_(isinstance(creative_placement_assignments, tuple))
 def testCreateCreative(self):
     """Test whether we can create a creative."""
     creative = {
         'type': 'ImageCreative',
         'name': 'Image Creative #%s' % Utils.GetUniqueName(),
         'advertiserId': self.__class__.advertiser_id,
         'destinationUrl': 'http://google.com',
         'imageName': 'image.jpg',
         'imageByteArray': self.__class__.IMAGE_DATA1,
         'size': {
             'width': '300',
             'height': '250'
         }
     }
     self.assert_(
         isinstance(self.__class__.service.CreateCreative(creative), tuple))
def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id):
    """ Create a Campaign with a Shared Bidding Strategy.

  Args:
    client: AdWordsClient the client to run the example with.
    bidding_strategy_id: string the bidding strategy ID to use.
    shared_budget_id: string the shared budget ID to use.

  Returns:
    dict An object representing a campaign.
  """
    # Initialize appropriate service.
    campaign_service = client.GetCampaignService(version='v201406')

    # Create campaign.
    campaign = {
        'name': 'Interplanetary Cruise #%s' % Utils.GetUniqueName(),
        'advertisingChannelType': 'SEARCH',
        'budget': {
            'budgetId': budget_id
        },
        'biddingStrategyConfiguration': {
            'biddingStrategyId': bidding_strategy_id
        },
        'settings': [{
            'xsi_type': 'KeywordMatchSetting',
            'optIn': 'true'
        }],
        'networkSetting': {
            'targetGoogleSearch': 'true',
            'targetSearchNetwork': 'true',
            'targetContentNetwork': 'true'
        }
    }

    # Create operation.
    operation = {'operator': 'ADD', 'operand': campaign}

    response = campaign_service.mutate([operation])[0]
    new_campaign = response['value'][0]

    print('Campaign with name \'%s\', ID \'%s\' and bidding scheme ID \'%s\' '
          'was created.' %
          (new_campaign['name'], new_campaign['id'],
           new_campaign['biddingStrategyConfiguration']['biddingStrategyId']))

    return new_campaign
    def __GenerateHeaders(self,
                          return_micros=None,
                          skip_report_header=None,
                          skip_report_summary=None):
        """Generates the headers to use for the report download.

    Args:
      return_micros: bool whether or not to use micros for money.
      skip_report_header: A boolean indicating whether to include a header row
          containing the report name and date range. If false or not specified,
          report output will include the header row.
      skip_report_summary: A boolean indicating whether to include a summary row
          containing the report totals. If false or not specified, report output
          will include the summary row.

    Returns:
      dict Dictionary containing all the headers for the request
    """
        headers = {}
        if 'clientCustomerId' in self._headers:
            headers['clientCustomerId'] = self._headers['clientCustomerId']

        # Apply OAuth2 headers
        self._headers['oauth2credentials'].apply(headers)

        if skip_report_header:
            headers.update({'skipReportHeader': str(skip_report_header)})

        if skip_report_summary:
            headers.update({'skipReportSummary': str(skip_report_summary)})

        if return_micros is not None:
            if self._op_config[
                    'version'] == FINAL_RETURN_MONEY_IN_MICROS_VERSION:
                headers['returnMoneyInMicros'] = str(return_micros)
            else:
                raise AdWordsError(
                    'returnMoneyInMicros isn\'t supported in this'
                    ' version.')

        headers['developerToken'] = self._headers['developerToken']
        headers['User-Agent'] = self._headers['userAgent']
        if Utils.BoolTypeConvert(self._config['compress']):
            headers['Accept-Encoding'] = 'gzip'
            headers['User-Agent'] += ',gzip'
            headers['Content-Encoding'] = 'gzip'
        return headers
    def _SetHeaders(self):
        """Sets the SOAP headers for this service's requests."""
        now = time.time()
        if ((('authToken' not in self._headers
              and 'auth_token_epoch' not in self._config) or
             int(now - self._config['auth_token_epoch']) >= AUTH_TOKEN_EXPIRE)
                and not self._headers.get('oauth2credentials')):
            if ('email' not in self._headers or not self._headers['email']
                    or 'password' not in self._headers
                    or not self._headers['password']):
                raise ValidationError(
                    'Required authentication headers, \'email\' and '
                    '\'password\', are missing. Unable to regenerate '
                    'authentication token.')
            self._headers['authToken'] = Utils.GetAuthToken(
                self._headers['email'], self._headers['password'],
                AUTH_TOKEN_SERVICE, LIB_SIG, self._config['proxy'])
            self._config['auth_token_epoch'] = time.time()

        # Apply headers to the SOAPpy service.
        soap_headers = SOAPpy.Types.headerType(
            attrs={'xmlns': self._namespace})
        request_header_data = {}
        if 'authToken' in self._headers:
            authentication_block = SOAPpy.Types.structType(
                data={'token': self._headers['authToken']},
                name='authentication',
                typed=0,
                attrs={(SOAPpy.NS.XSI3, 'type'): 'ClientLogin'})
            request_header_data['authentication'] = authentication_block
        for key in self._headers:
            if (key in GenericDfpService._IGNORED_HEADER_VALUES
                    or not self._headers[key]):
                continue
            value = self._headers[key]
            if key == 'applicationName':
                value = ''.join([value, LIB_SIG])
            request_header_data[key] = SOAPpy.Types.stringType(value)
        request_header = SOAPpy.Types.structType(data=request_header_data,
                                                 name='RequestHeader',
                                                 typed=0)
        soap_headers.RequestHeader = request_header
        if 'authToken' in self._headers:
            soap_headers.RequestHeader._keyord = [
                'applicationName', 'authentication'
            ]
        self._soappyservice.soapproxy.header = soap_headers
Exemple #22
0
    def __init__(self,
                 client_id,
                 client_secret,
                 refresh_token,
                 mcc_cid,
                 dev_token,
                 debug=False):
        """Initializes an APIHandler.

    Args:
      client_id:
      client_secret:
      refresh_token:
      mcc_cid:
      dev_token:
      debug:
    """
        credentials = OAuth2Credentials(None, client_id, client_secret,
                                        refresh_token, None, self._REFRESH_URL,
                                        self._USER_AGENT)
        credentials.refresh(httplib2.Http())

        headers = {
            'clientCustomerId': mcc_cid,
            'userAgent': self._USER_AGENT,
            'developerToken': dev_token,
            'validateOnly': 'n',
            'partialFailure': 'n',
            'oauth2credentials': credentials
        }
        # App Engine doesn't allow you to write to the disk. Thus, we need to
        # explicitly turn off logging. Though, if debugging is enabled, the
        # data from STDOUT will be redirected to app engine's debugging console.
        # Note that we also specify that we want to use ElementTree here; see the
        # README for more information if you would rather use PyXML.
        config = {
            'debug': Utils.BoolTypeConvert(debug),
            'xml_log': 'n',
            'request_log': 'n',
            'pretty_xml': 'n',
            'xml_parser': '2',  # We're using ElementTree.
            'compress': 'n'
        }

        self.client = AdWordsClient(headers, config)
        self.client.use_mcc = True
 def testSaveSpotlightActivity(self):
     """Test whether we can save a spotlight activity."""
     if self.__class__.activity_group_id == '0':
         self.testSaveSpotlightActivityGroup()
     activity_group_id = self.__class__.activity_group_id
     spotlight_activity = {
         'name': 'SpotlightActivity #%s' % Utils.GetUniqueName(),
         'activityGroupId': activity_group_id,
         'activityTypeId': '1',  # Counter Activity
         'tagMethodTypeId': '1',  # Standard
         'expectedUrl': 'http://www.example.com',
         'countryId': '256'  #USA
     }
     spotlight_activity = self.__class__.service.SaveSpotlightActivity(
         spotlight_activity)
     self.__class__.activity_id = spotlight_activity[0]['id']
     self.assert_(isinstance(spotlight_activity, tuple))
Exemple #24
0
 def testSaveUserRole(self):
     """Test whether we can save a user role"""
     subnetwork_id = self.__class__.user_self['subnetworkId']
     user_group_id = self.__class__.user_self['userGroupId']
     user_role = {
         'name': 'UserRole #%s' % Utils.GetUniqueName(),
         'subnetworkId': subnetwork_id,
         'parentUserRoleId': user_group_id,
         'permissions': [{
             'id': '2068'
         }, {
             'id': '2037'
         }]
     }
     user_role = self.__class__.service.SaveUserRole(user_role)
     self.__class__.user_role_id = user_role[0]['id']
     self.assert_(isinstance(user_role, tuple))
def main(client, advertiser_id):
  # Initialize appropriate service.
  creative_service = client.GetService('CreativeService', version='v201411')

  # Create creative objects.
  creatives = []
  with open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data',
                         'medium_rectangle.jpg'), 'r') as image:
    image_data = base64.encodestring(image.read())

  for i in xrange(5):
    # Create creative size.
    size = {
        'width': '300',
        'height': '250'
    }

    # Create image asset.
    creative_asset = {
        'type': 'CreativeAsset',
        'fileName': 'image.jpg',
        'assetByteArray': image_data,
        'size': size
    }

    # Create an image creative.
    creative = {
        'type': 'ImageCreative',
        'name': 'Image Creative #%s' % Utils.GetUniqueName(),
        'advertiserId': advertiser_id,
        'destinationUrl': 'http://google.com',
        'size': size,
        'primaryImageAsset': creative_asset
    }

    creatives.append(creative)

  # Add creatives.
  creatives = creative_service.CreateCreatives(creatives)

  # Display results.
  for creative in creatives:
    print ('Image creative with id \'%s\', name \'%s\', and type \'%s\' was '
           'created and can be previewed at %s.'
           % (creative['id'], creative['name'], creative['Creative_Type'],
              creative['previewUrl']))
    def setUp(self):
        """Prepare unittest."""
        print self.id()
        if not self.__class__.service:
            self.__class__.service = client.GetCreativeService(
                self.__class__.SERVER, self.__class__.VERSION, HTTP_PROXY)

        if self.__class__.advertiser_id == '0':
            company = {
                'name': 'Company #%s' % Utils.GetUniqueName(),
                'type': 'ADVERTISER'
            }
            company_service = client.GetCompanyService(self.__class__.SERVER,
                                                       self.__class__.VERSION,
                                                       HTTP_PROXY)
            self.__class__.advertiser_id = company_service.CreateCompany(
                company)[0]['id']
Exemple #27
0
def _SanityCheckArray(wsdl_types, obj, xsi_type):
    """Validates a list representing an array type against its WSDL definition.

  Args:
    wsdl_types: dict WSDL-defined types in the same service as the given type.
    obj: list List representing the given array type.
    xsi_type: str The array type name defined in the WSDL.
  """
    ValidateTypes(((obj, list), ))
    if Utils.IsXsdOrSoapenc(wsdl_types[xsi_type]['base_type']):
        for item in obj:
            if item is None: continue
            ValidateTypes(((item, (str, unicode)), ))
    else:
        for item in obj:
            if item is None: continue
            NewSanityCheck(wsdl_types, item, wsdl_types[xsi_type]['base_type'])
    def __PrettyPrintXml(self, doc, level=0):
        """Return a pretty-printed version of the XML document.

    Args:
      doc: str XML document.
      level: int Level of prettiness, defaults to 0. If -1, remove prettiness.

    Returns:
      str Pretty-printed version of the XML document.
    """
        # Make sure we have a valid doc to work with.
        if Utils.IsHtml(doc):
            return doc

        try:
            if self.__xml_parser == PYXML:
                dom = minidom.parseString(doc)
                pretty_doc = dom.toprettyxml(indent=' ', encoding='UTF-8')
            elif self.__xml_parser == ETREE:
                tree = etree.fromstring(doc)
                self.__Indent(tree)
                pretty_doc = etree.tostring(tree, 'UTF-8')
        except (ExpatError, SyntaxError):
            # If there was a problem with loading XML message into a DOM, return
            # original XML message.
            return doc

        # Adjust prettiness of data values in the XML document.
        #
        # Before:  <operations>
        #            0
        #          </operations>
        #
        # After:   <operations>0</operations>
        pattern = re.compile('\n\s+\n')
        pretty_doc = pattern.sub('\n', pretty_doc)
        groups = re.findall('>(\n\s+(.*?)\n\s+)</', pretty_doc, re.M)
        for old, new in groups:
            if old and new and (new.find('<') > -1 or new.find('>') > -1):
                continue
            pretty_doc = pretty_doc.replace(old, new)

        if level == -1:
            pattern = re.compile('>\s+<')
            pretty_doc = pattern.sub('><', pretty_doc)
        return pretty_doc.strip('\n')
    def _SetHeaders(self):
        """Sets the SOAP headers for this service's requests."""
        now = time.time()
        if ((('authToken' not in self._headers
              and 'auth_token_epoch' not in self._config) or
             int(now - self._config['auth_token_epoch']) >= AUTH_TOKEN_EXPIRE)
                and not self._headers.get('oauth2credentials')):
            if ('email' not in self._headers or not self._headers['email']
                    or 'password' not in self._headers
                    or not self._headers['password']):
                raise ValidationError(
                    'Required authentication headers, \'email\' and '
                    '\'password\', are missing. Unable to regenerate '
                    'authentication token.')
            self._headers['authToken'] = Utils.GetAuthToken(
                self._headers['email'], self._headers['password'],
                AUTH_TOKEN_SERVICE, LIB_SIG, self._config['proxy'])
            self._config['auth_token_epoch'] = time.time()

        # Apply headers to the SOAPpy service.
        header_attrs = {
            'xmlns':
            self._namespace,
            'xmlns:cm': ('https://adwords.google.com/api/adwords/cm/' +
                         self._op_config['version'])
        }
        soap_headers = SOAPpy.Types.headerType(attrs=header_attrs)
        request_header_data = {}
        for key in GenericAdWordsService._POSSIBLE_ADWORDS_REQUEST_HEADERS:
            if (key in GenericAdWordsService._OAUTH_IGNORE_HEADERS
                    and self._headers.get('oauth2credentials')):
                continue
            if key in self._headers and self._headers[key]:
                value = self._headers[key]
                if key in GenericAdWordsService._STR_CONVERT:
                    value = str(value)
                elif key == 'userAgent':
                    value = ''.join([value, LIB_SIG])
                request_header_data['cm:' +
                                    key] = SOAPpy.Types.stringType(value)
        request_header = SOAPpy.Types.structType(data=request_header_data,
                                                 name='RequestHeader',
                                                 typed=0)
        soap_headers.RequestHeader = request_header
        self._soappyservice.soapproxy.header = soap_headers
def _PackStringAsXml(obj, xml_tag_name):
    """Pack a Python string into an XML string.

  Args:
    obj: str Python string to pack.
    xml_tag_name: str The name of the XML tag that will house this string.

  Returns:
    str An XML element representing the given string.
  """
    if obj is None:
        return '<%s xsi3:nil="true" />' % (xml_tag_name)
    else:
        obj = Utils.HtmlEscape(obj)
        if xml_tag_name:
            return '<%s>%s</%s>' % (xml_tag_name, obj, xml_tag_name)
        else:
            return obj