Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

  1. Add update_line_items_rate.py to the tasks folder. It accepts/reads the line item ID, the new rate, and calls the function defined in dfp directory to update line items:

    Code Block
    languagepy
    titleSample update_line_items_rate.py
    linenumberstrue
    collapsetrue
    """This code example updates the rate of line item.
    """
    import dfp.update_line_item
     
     
    # Set id of the line item.
    LINE_ITEM_ID = 'INSERT_LINE_ITEM_ID_HERE'
     
    #set rate of the line item
    RATE = 'INSERT_RATE_HERE'
     
     
    def main( line_item_id, rate):
       
      #convert rate to micro amount
      rate = num_to_micro_amount(float(rate))
     
      #calling DFP (GAM) method to update line item
      dfp.update_line_item.update_line_item_rate(line_item_id, rate)
     
    def num_to_micro_amount(num, precision=2):
      """
      Converts a number into micro-amounts (multiplied by 1M), rounded to
      specified precision. Useful for more easily working with currency,
      and also for communicating with DFP(GAM)API.
     
      Args:
        num (float or int)
        precision (int)
      Returns:
        an integer: int(num * 1,000,000), rounded to the nearest
          10^(6-`precision`)
      """
      rounding = -6 + precision
      return int(round(num * (10 ** 6), rounding))
     
    if __name__ == '__main__':
      main(LINE_ITEM_ID, RATE)


  2. Add update_line_items.py to the dfp folder. It gets the line item from the GAM account, forms the updated line item config, and calls the GAM line item service to update the line item.

    Code Block
    languagepy
    titleSample update_line_items.py
    linenumberstrue
    collapsetrue
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
     
    import logging
     
    from googleads import ad_manager
     
    from dfp.client import get_client
     
     
    logger = logging.getLogger(__name__)
     
    def update_line_item_rate(line_item_id, rate):
     
      dfp_client = get_client()
      line_item_service = dfp_client.GetService('LineItemService', version='v201911')
     
      # Create statement object to get line item.
      statement = (ad_manager.StatementBuilder(version='v201911')
                   .Where(('id = :id '))
                   .WithBindVariable('id', int(line_item_id)))
     
      # Get line items by statement.
      response = line_item_service.getLineItemsByStatement(
          statement.ToStatement())
      print(response)
      if 'results' in response and len(response['results']):
        # Update each local line item by changing its delivery rate type.
        updated_line_items = []
        for line_item in response['results']:
          if not line_item['isArchived']:
            line_item['costPerUnit']['microAmount'] = rate
            updated_line_items.append(line_item)
     
        # Update line items remotely.
        line_items = line_item_service.updateLineItems(updated_line_items)
        if line_items:
          for line_item in line_items:
            print('Line item with id "%s", belonging to order id "%s", named '
                  '"%s", and rate "%s" was updated.'
                  % (line_item['id'], line_item['orderId'], line_item['name'],
                      line_item['costPerUnit']['microAmount']))
        else:
          print('No line items were updated.')
      else:
        print('No line items found to update.')
     
    def main():
        print("update line items")
     
    if __name__ == '__main__':
      main()

    For GAM-related code, see the sample code available in, https://github.com/googleads/googleads-python-lib/tree/master/examples/ad_manager/v201911v202102. For line item update see, Update Line Item Example.

    Using the Line Item Tool's modular framework, you can support a wide range of custom requirements and also contribute to extending and improving this tool.