示例#1
0
def main(client):
  # Initialize appropriate service.
  creative_service = client.GetService('CreativeService', version='v201708')

  # Create a statement to get the image creative.
  statement = (dfp.StatementBuilder()
               .Where('id = :id')
               .OrderBy('id', ascending=True)
               .WithBindVariable('id', CREATIVE_ID))

  # Get the creative.
  query_result = creative_service.getCreativesByStatement(
      statement.ToStatement())

  image_creative = query_result['results'][0]

  # Build the new creative, set id to None to create a copy.
  image_creative['id'] = None
  image_creative['name'] = 'Copy of %s' % image_creative['name']

  result = creative_service.createCreatives([image_creative])[0]
  print ('A creative with ID %d, name "%s", and type "%s" was created and '
         'can be previewed at: %s' % (result['id'],
                                      result['name'],
                                      dfp.DfpClassType(result),
                                      result['previewUrl']))
def main(client, rate_card_id):
    # Initialize appropriate service.
    base_rate_service = client.GetService('BaseRateService', version='v201605')

    # Create a filter statement for base rates for a single rate card.
    values = [{
        'key': 'rateCardId',
        'value': {
            'xsi_type': 'NumberValue',
            'value': rate_card_id
        }
    }]
    query = 'where rateCardId = :rateCardId ORDER BY id ASC'
    statement = dfp.FilterStatement(query, values)

    # Get base rates by statement.
    while True:
        response = base_rate_service.getBaseRatesByStatement(
            statement.ToStatement())
        if 'results' in response:
            # Display results.
            for base_rate in response['results']:
                print(
                    'Base rate with ID \'%s\' and type \'%s\' belonging to '
                    'rate card ID \'%s\' was found.' %
                    (base_rate['id'], dfp.DfpClassType(base_rate),
                     base_rate['rateCardId']))
            statement.offset += dfp.SUGGESTED_PAGE_LIMIT
        else:
            break

    print '\nNumber of results found: %s' % response['totalResultSetSize']
def main(client, rate_card_id):
    # Initialize appropriate service.
    premium_rate_service = client.GetService('PremiumRateService',
                                             version='v201605')

    # Create statement object to select a single proposal by an ID.
    values = [{
        'key': 'rateCardId',
        'value': {
            'xsi_type': 'NumberValue',
            'value': rate_card_id
        }
    }]
    query = 'WHERE rateCardId = :rateCardId ORDER BY id ASC'
    statement = dfp.FilterStatement(query, values)

    # Get premium rates by statement.
    while True:
        response = premium_rate_service.getPremiumRatesByStatement(
            statement.ToStatement())
        if 'results' in response:
            # Display results.
            for premium_rate in response['results']:
                print(
                    'Premium rate with ID \'%s\' of type \'%s\' assigned to '
                    ' rate card with ID \'%s\' was found.\n' %
                    (premium_rate['id'],
                     dfp.DfpClassType(premium_rate['premiumFeature']),
                     premium_rate['rateCardId']))
            statement.offset += dfp.SUGGESTED_PAGE_LIMIT
        else:
            break

    print '\nNumber of results found: %s' % response['totalResultSetSize']
def main(client):
  # Initialize appropriate service.
  premium_rate_service = client.GetService('PremiumRateService',
                                           version='v201602')

  # Create a filter statement.
  statement = dfp.FilterStatement('ORDER BY id ASC')

  # Get premium rates by statement.
  while True:
    response = premium_rate_service.getPremiumRatesByStatement(
        statement.ToStatement())
    if 'results' in response:
      # Display results.
      for premium_rate in response['results']:
        print ('Premium rate with ID \'%s\' of type \'%s\' assigned to '
               ' rate card with ID \'%s\' was found.\n' % (
                   premium_rate['id'],
                   dfp.DfpClassType(premium_rate['premiumFeature']),
                   premium_rate['rateCardId']))
      statement.offset += dfp.SUGGESTED_PAGE_LIMIT
    else:
      break

  print '\nNumber of results found: %s' % response['totalResultSetSize']
示例#5
0
def main(client, rate_card_id):
    # Initialize appropriate service.
    base_rate_service = client.GetService('BaseRateService', version='v201711')
    # Create a statement to select base rates.
    statement = (dfp.StatementBuilder().Where(
        'rateCardId = :rateCardId').WithBindVariable('rateCardId',
                                                     rate_card_id))

    # Retrieve a small amount of base rates at a time, paging
    # through until all base rates have been retrieved.
    while True:
        response = base_rate_service.getBaseRatesByStatement(
            statement.ToStatement())
        if 'results' in response:
            for base_rate in response['results']:
                # Print out some information for each base rate.
                print(
                    'Base rate with ID "%d", type "%s", and rate card ID "%d" was '
                    'found.\n' % (base_rate['id'], dfp.DfpClassType(base_rate),
                                  base_rate['rateCardId']))
            statement.offset += dfp.SUGGESTED_PAGE_LIMIT
        else:
            break

    print '\nNumber of results found: %s' % response['totalResultSetSize']
def main(client):
  # Initialize appropriate service.
  premium_rate_service = client.GetService(
      'PremiumRateService', version='v201805')

  # Create a statement to select premium rates.
  statement = dfp.StatementBuilder()

  # Retrieve a small amount of premium rates at a time, paging
  # through until all premium rates have been retrieved.
  while True:
    response = premium_rate_service.getPremiumRatesByStatement(
        statement.ToStatement())
    if 'results' in response:
      for premium_rate in response['results']:
        # Print out some information for each premium rate.
        print('Premium rate with ID "%d", premium feature "%s", and rate card '
              'id "%d" was found.\n' % (premium_rate['id'],
                                        dfp.DfpClassType(premium_rate),
                                        premium_rate['rateCardId']))
      statement.offset += statement.limit
    else:
      break

  print '\nNumber of results found: %s' % response['totalResultSetSize']
def main(client, rate_card_id):
    # Initialize appropriate service.
    base_rate_service = client.GetService('BaseRateService', version='v201608')
    query = 'WHERE rateCardId = :rateCardId'
    values = [
        {
            'key': 'rateCardId',
            'value': {
                'xsi_type': 'TextValue',
                'value': rate_card_id
            }
        },
    ]
    # Create a statement to select base rates.
    statement = dfp.FilterStatement(query, values)

    # Retrieve a small amount of base rates at a time, paging
    # through until all base rates have been retrieved.
    while True:
        response = base_rate_service.getBaseRatesByStatement(
            statement.ToStatement())
        if 'results' in response:
            for base_rate in response['results']:
                # Print out some information for each base rate.
                print(
                    'Base rate with ID "%d", type "%s", and rate card ID "%d" was '
                    'found.\n' % (base_rate['id'], dfp.DfpClassType(base_rate),
                                  base_rate['rateCardId']))
            statement.offset += dfp.SUGGESTED_PAGE_LIMIT
        else:
            break

    print '\nNumber of results found: %s' % response['totalResultSetSize']
def main(client):
    # Initialize appropriate service.
    creative_service = client.GetService('CreativeService', version='v201505')

    # Create statement object to only select image creatives.
    values = [{
        'key': 'creativeType',
        'value': {
            'xsi_type': 'TextValue',
            'value': 'ImageCreative'
        }
    }]
    query = 'WHERE creativeType = :creativeType'
    statement = dfp.FilterStatement(query, values)

    # Get creatives by statement.
    while True:
        response = creative_service.getCreativesByStatement(
            statement.ToStatement())
        creatives = response['results']

        if creatives:
            # Display results.
            for creative in creatives:
                print((
                    'Creative with id \'%s\', name \'%s\', and type \'%s\' was '
                    'found.' % (creative['id'], creative['name'],
                                dfp.DfpClassType(creative))))
            statement.offset += dfp.SUGGESTED_PAGE_LIMIT
        else:
            break

    print('\nNumber of results found: %s' % response['totalResultSetSize'])
示例#9
0
def main(client, advertiser_id):
  # Initialize appropriate service.
  creative_service = client.GetService('CreativeService', version='v201605')

  # Use the image banner with optional third party tracking template.
  creative_template_id = '10000680'

  image_data = open(os.path.join(os.path.split(__file__)[0], '..', '..', 'data',
                                 'medium_rectangle.jpg'), 'r').read()
  image_data = base64.encodestring(image_data)
  # Create creative from templates.
  creative = {
      'xsi_type': 'TemplateCreative',
      'name': 'Template Creative #%s' % uuid.uuid4(),
      'advertiserId': advertiser_id,
      'size': {'width': '300', 'height': '250'},
      'creativeTemplateId': creative_template_id,
      'creativeTemplateVariableValues': [
          {
              'xsi_type': 'AssetCreativeTemplateVariableValue',
              'uniqueName': 'Imagefile',
              'assetByteArray': image_data,
              'fileName': 'image%s.jpg' % uuid.uuid4()
          },
          {
              'xsi_type': 'LongCreativeTemplateVariableValue',
              'uniqueName': 'Imagewidth',
              'value': '300'
          },
          {
              'xsi_type': 'LongCreativeTemplateVariableValue',
              'uniqueName': 'Imageheight',
              'value': '250'
          },
          {
              'xsi_type': 'UrlCreativeTemplateVariableValue',
              'uniqueName': 'ClickthroughURL',
              'value': 'www.google.com'
          },
          {
              'xsi_type': 'StringCreativeTemplateVariableValue',
              'uniqueName': 'Targetwindow',
              'value': '_blank'
          }
      ]
  }

  # Call service to create the creative.
  creative = creative_service.createCreatives([creative])[0]

  # Display results.
  print ('Template creative with id \'%s\', name \'%s\', and type \'%s\' was '
         'created and can be previewed at %s.'
         % (creative['id'], creative['name'], dfp.DfpClassType(creative),
            creative['previewUrl']))
def main(client, advertiser_id):
    # Initialize appropriate service.
    creative_service = client.GetService('CreativeService', version='v201702')

    # Get the image data for the creative.
    image_data = open(
        os.path.join(
            os.path.split(__file__)[0], '..', '..', 'data',
            'medium_rectangle.jpg'), 'r').read()
    image_data = base64.encodestring(image_data)

    # Create the HTML snippet used in the custom creative.
    html_snippet = (
        '<a href=\'%s%s\'><img src=\'%s\'/></a><br>Click above for '
        'great deals!') % ('%%CLICK_URL_UNESC%%', '%%DEST_URL%%',
                           '%%FILE:IMAGE_ASSET%%')

    # Create custom creative.
    creative = {
        'xsi_type':
        'CustomCreative',
        'name':
        'Custom Creative #%s' % uuid.uuid4(),
        'advertiserId':
        advertiser_id,
        'size': {
            'width': '300',
            'height': '250'
        },
        'destinationUrl':
        'http://google.com',
        'customCreativeAssets': [{
            'xsi_type': 'CustomCreativeAsset',
            'macroName': 'IMAGE_ASSET',
            'asset': {
                'assetByteArray': image_data,
                'fileName': 'image%s.jpg' % uuid.uuid4()
            }
        }],
        'htmlSnippet':
        html_snippet
    }

    # Call service to create the creative.
    creatives = creative_service.createCreatives([creative])

    # Display results.
    if creatives:
        creative = creatives[0]
        print(
            'Template creative with id \'%s\', name \'%s\', and type \'%s\' was '
            'created and can be previewed at %s.' %
            (creative['id'], creative['name'], dfp.DfpClassType(creative),
             creative['previewUrl']))
示例#11
0
def main(client, rate_card_id):
  # Initialize appropriate services.
  premium_rate_service = client.GetService('PremiumRateService',
                                           version='v201711')

  # Create an ad unit premium to apply to the rate card.
  ad_unit_premium_feature = {
      'xsi_type': 'AdUnitPremiumFeature'
  }

  # Create a CPC based premium rate value with adjustments in milli amounts.
  # This will adjust a CPC priced proposal line item that has
  # inventory targeting specified by 10% of the cost associated with the rate
  # card (this comes from a percentage adjustment).
  cpc_premium_rate_value = {
      'premiumFeature': ad_unit_premium_feature,
      'rateType': 'CPC',
      'adjustmentSize': 10000,
      'adjustmentType': 'PERCENTAGE'
  }

  # Create a CPM based premium rate value with adjustments in micro amounts.
  # This will adjust a CPM priced proposal line item that has
  # inventory targeting specified by 2 units of the currency associated with
  # the rate card (this comes from absolute value adjustment).
  cpm_premium_rate_value = {
      'premiumFeature': ad_unit_premium_feature,
      'rateType': 'CPM',
      'adjustmentSize': 2000000,
      'adjustmentType': 'ABSOLUTE_VALUE'
  }

  # Create premium rate.
  # Associate premium rate with the rate card and set premium information.
  # This premium will apply for proposal line items targeting 'any' ad unit
  # for both CPM and CPC rate types.
  premium_rate = {
      'rateCardId': rate_card_id,
      'pricingMethod': 'ANY_VALUE',
      'premiumFeature': ad_unit_premium_feature,
      'premiumRateValues': [cpc_premium_rate_value, cpm_premium_rate_value]
  }

  # Add premium_rates.
  premium_rates = premium_rate_service.createPremiumRates([premium_rate])

  # Display results.
  for premium_rate in premium_rates:
    print ('A premium rate for "%s" was added to the rate card with ID'
           ' of "%s".\n'
           % (dfp.DfpClassType(premium_rate['premiumFeature']),
              premium_rate['id']))
def main(client, base_rate_id):
  # Initialize appropriate service.
  base_rate_service = client.GetService('BaseRateService', version='v201505')

  # Create a filter statement for base rates for a single rate card.
  values = [{
      'key': 'id',
      'value': {
          'xsi_type': 'NumberValue',
          'value': base_rate_id
      }
  }]
  query = 'where id = :id ORDER BY id ASC'
  statement = dfp.FilterStatement(query, values, 1)

  # Get single base rate by statement.
  response = base_rate_service.getBaseRatesByStatement(
      statement.ToStatement())

  if 'results' in response:
    # Update each local base rate object by changing its value to $3 USD.
    new_rate = {
        'currencyCode': 'USD',
        'microAmount': 3000000
    }

    updated_base_rates = []
    for base_rate in response['results']:
      base_rate['rate'] = new_rate
      updated_base_rates.append(base_rate)

    # Update base rates remotely.
    base_rates = base_rate_service.updateBaseRates(updated_base_rates)

    # Display results.
    if base_rates:
      for base_rate in base_rates:
        print ('Base rate with ID \'%s\' and type \'%s\' belonging to '
               'rate card ID \'%s\' was updated.' % (
                   base_rate['id'],
                   dfp.DfpClassType(base_rate),
                   base_rate['rateCardId']))
    else:
      print 'No base rates were updated.'
  else:
    print 'No base rates found to update.'
示例#13
0
def main(client, advertiser_id):
    # Initialize appropriate service.
    creative_service = client.GetService('CreativeService', version='v201505')

    # 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 range(5):
        # Create creative size.
        size = {'width': '300', 'height': '250'}

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

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

        creatives.append(creative)

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

    # Display results.
    for creative in creatives:
        print(
            ('Image creative with id \'%s\', name \'%s\', and type \'%s\' was '
             'created and can be previewed at %s.' %
             (creative['id'], creative['name'], dfp.DfpClassType(creative),
              creative['previewUrl'])))
def main(client, base_rate_id):
  # Initialize appropriate service.
  base_rate_service = client.GetService('BaseRateService', version='v201802')

  # Create a filter statement for base rates for a single rate card.
  statement = (dfp.StatementBuilder()
               .Where('id = :id')
               .OrderBy('id', ascending=True)
               .Limit(1)
               .WithBindVariable('id', long(base_rate_id)))

  # Get single base rate by statement.
  response = base_rate_service.getBaseRatesByStatement(
      statement.ToStatement())

  if 'results' in response:
    # Update each local base rate object by changing its value to $3 USD.
    new_rate = {
        'currencyCode': 'USD',
        'microAmount': 3000000
    }

    updated_base_rates = []
    for base_rate in response['results']:
      base_rate['rate'] = new_rate
      updated_base_rates.append(base_rate)

    # Update base rates remotely.
    base_rates = base_rate_service.updateBaseRates(updated_base_rates)

    # Display results.
    if base_rates:
      for base_rate in base_rates:
        print ('Base rate with ID "%s" and type "%s" belonging to '
               'rate card ID "%s" was updated.' % (
                   base_rate['id'],
                   dfp.DfpClassType(base_rate),
                   base_rate['rateCardId']))
    else:
      print 'No base rates were updated.'
  else:
    print 'No base rates found to update.'
示例#15
0
def ConvertValueForCsv(pql_value):
    """Sanitizes a field value from a Value object to a CSV suitable format.

  Args:
    pql_value: dict a dictionary containing the data for a single field of an
                 entity.

  Returns:
    str a CSV writer friendly value formatted by Value.Type.
  """
    if 'value' in pql_value:
        field = pql_value['value']
    elif 'values' in pql_value:
        field = pql_value['values']
    else:
        field = None

    if field:
        if isinstance(field, list):
            return ','.join([
                '"%s"' % str(ConvertValueForCsv(single_field))
                for single_field in field
            ])
        else:
            class_type = dfp.DfpClassType(pql_value)

            if class_type == 'TextValue':
                return field.replace('"', '""').encode('UTF8')
            elif class_type == 'NumberValue':
                return float(field) if '.' in field else int(field)
            elif class_type == 'DateTimeValue':
                return ConvertDateTimeToOffset(field)
            elif class_type == 'DateValue':
                return date(int(field['date']['year']),
                            int(field['date']['month']),
                            int(field['date']['day'])).isoformat()
            else:
                return field
    else:
        return '-'
def main(client):
  # Initialize appropriate service.
  creative_service = client.GetService('CreativeService', version='v201502')

  # Create statement object to select all creatives.
  statement = dfp.FilterStatement()

  # Get creatives by statement.
  while True:
    response = creative_service.getCreativesByStatement(
        statement.ToStatement())
    if 'results' in response:
      # Display results.
      for creative in response['results']:
        print ('Creative with id \'%s\', name \'%s\', and type \'%s\' was '
               'found.' % (creative['id'], creative['name'],
                           dfp.DfpClassType(creative)))
      statement.offset += dfp.SUGGESTED_PAGE_LIMIT
    else:
      break

  print '\nNumber of results found: %s' % response['totalResultSetSize']
def main(client):
    # Initialize appropriate service.
    base_rate_service = client.GetService('BaseRateService', version='v201502')

    # Create a filter statement.
    statement = dfp.FilterStatement('ORDER BY id ASC')

    # Get base rates by statement.
    while True:
        response = base_rate_service.getBaseRatesByStatement(
            statement.ToStatement())
        if 'results' in response:
            # Display results.
            for base_rate in response['results']:
                print(('Base rate with ID \'%s\' and type \'%s\' belonging to '
                       'rate card ID \'%s\' was found.' %
                       (base_rate['id'], dfp.DfpClassType(base_rate),
                        base_rate['rateCardId'])))
            statement.offset += dfp.SUGGESTED_PAGE_LIMIT
        else:
            break

    print('\nNumber of results found: %s' % response['totalResultSetSize'])
示例#18
0
def main(client, custom_field_id, drop_down_custom_field_id,
         custom_field_option_id, line_item_id):
    # Initialize appropriate services.
    custom_field_service = client.GetService('CustomFieldService',
                                             version='v201608')

    line_item_service = client.GetService('LineItemService', version='v201608')

    # Create statement to get a custom field.
    custom_field_values = [{
        'key': 'customFieldId',
        'value': {
            'xsi_type': 'NumberValue',
            'value': custom_field_id
        }
    }]
    custom_field_query = 'WHERE id = :customFieldId'
    custom_field_statement = dfp.FilterStatement(custom_field_query,
                                                 custom_field_values, 1)

    # Get custom field.
    custom_field = custom_field_service.getCustomFieldsByStatement(
        custom_field_statement.ToStatement())['results'][0]

    # Create statement to get a drop down custom field.
    drop_down_custom_field_values = [{
        'key': 'dropDownCustomFieldId',
        'value': {
            'xsi_type': 'NumberValue',
            'value': drop_down_custom_field_id
        }
    }]
    drop_down_custom_field_query = 'WHERE id = :dropDownCustomFieldId'
    drop_down_custom_field_statement = dfp.FilterStatement(
        drop_down_custom_field_query, drop_down_custom_field_values, 1)

    # Get drop-down custom field.
    drop_down_custom_field = custom_field_service.getCustomFieldsByStatement(
        drop_down_custom_field_statement.ToStatement())['results'][0]

    # Create statement to get a line item.
    line_item_values = [{
        'key': 'lineItemId',
        'value': {
            'xsi_type': 'NumberValue',
            'value': line_item_id
        }
    }]
    line_item_query = 'WHERE id = :lineItemId'
    line_item_statement = dfp.FilterStatement(line_item_query,
                                              line_item_values, 1)

    # Get line item.
    line_item = line_item_service.getLineItemsByStatement(
        line_item_statement.ToStatement())['results'][0]

    if custom_field and line_item:
        # Create custom field values.
        custom_field_value = {
            'customFieldId': custom_field['id'],
            'xsi_type': 'CustomFieldValue',
            'value': {
                'xsi_type': 'TextValue',
                'value': 'Custom field value'
            }
        }

        drop_down_custom_field_value = {
            'customFieldId': drop_down_custom_field['id'],
            'xsi_type': 'DropDownCustomFieldValue',
            'customFieldOptionId': custom_field_option_id,
        }

        custom_field_values = [
            custom_field_value, drop_down_custom_field_value
        ]

        old_custom_field_values = []
        if 'customFieldValues' in line_item:
            old_custom_field_values = line_item['customFieldValues']

        # Only add existing custom field values for different custom fields than the
        # ones you are setting.
        for old_custom_field_value in old_custom_field_values:
            if (old_custom_field_value['customFieldId'] !=
                    custom_field_value['customFieldId']
                    and old_custom_field_value['customFieldId'] !=
                    drop_down_custom_field_value['customFieldId']):
                custom_field_values.append(old_custom_field_value)

        line_item['customFieldValues'] = custom_field_values

        # Update the line item on the server.
        line_items = line_item_service.updateLineItems([line_item])

        # Display results.
        for line_item in line_items:
            custom_field_value_strings = []
            for value in line_item['customFieldValues']:
                if dfp.DfpClassType(value) == 'CustomFieldValue':
                    custom_field_value_string = (
                        '{ID: \'%s\', value: \'%s\'}' %
                        (value['customFieldId'], value['value']['value']))
                elif dfp.DfpClassType(value) == 'DropDownCustomFieldValue':
                    custom_field_value_string = (
                        '{ID: \'%s\', custom field option ID: \'%s\'}' %
                        (value['customFieldId'], value['customFieldOptionId']))
                custom_field_value_strings.append(custom_field_value_string)
            print('Line item with ID \'%s\' set with custom field values %s.' %
                  (line_item['id'], ','.join(custom_field_value_strings)))
    else:
        print 'Line item or custom field not found.'