How to use the googleads.dfp function in googleads

To help you get started, we’ve selected a few googleads examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github linkedin / adfullssl / src / adscan / dfp.py View on Github external
days = datetime.date.today() - datetime.timedelta(days=days_ago)
    values.append({
      'key': 'date',
      'value': {
        'xsi_type': 'TextValue',
        'value': days.strftime('%Y-%m-%dT%H:%M:%S')
      }
    })
    print 'Only recently updated creatives will be downloaded.'
  else:
    print 'At most, %d creatives will be downloaded.' % len(creative_ids)

  id_str = ','.join(str(i) for i in creative_ids)

  statements = []
  for offset in range(offset, len(creative_ids), googleads.dfp.SUGGESTED_PAGE_LIMIT):
    statements.append({
      'query': 'WHERE %s id IN (%s) LIMIT %d OFFSET %d' % (date_setting, id_str, googleads.dfp.SUGGESTED_PAGE_LIMIT, offset),
      'values': values
    })
  return statements
github googleads / googleads-python-lib / examples / dfp / v201511 / line_item_creative_association_service / get_all_licas.py View on Github external
# Display results.
      for lica in response['results']:
        if 'creativeSetId' in lica:
          print ('LICA with line item ID \'%s\', creative set ID \'%s\', and '
                 'status \'%s\' was found.' %
                 (lica['lineItemId'], lica['creativeSetId'], lica['status']))
        else:
          print ('LICA with line item ID \'%s\', creative ID \'%s\', and status'
                 ' \'%s\' was found.' % (lica['lineItemId'], lica['creativeId'],
                                         lica['status']))

  print '\nNumber of results found: %s' % response['totalResultSetSize']

if __name__ == '__main__':
  # Initialize client object.
  dfp_client = dfp.DfpClient.LoadFromStorage()
  main(dfp_client)
github googleads / googleads-python-lib / examples / dfp / v201705 / publisher_query_language_service / get_recent_changes.py View on Github external
{
          'key': 'endDateTime',
          'value': {
              'xsi_type': 'DateTimeValue',
              'value': {
                  'date': {
                      'year': end_date.year,
                      'month': end_date.month,
                      'day': end_date.day
                  }
              }
          }
      }
  ]

  statement = dfp.FilterStatement(initial_query, values)
  keep_iterating = True
  i = 0
  total_rows = []

  while keep_iterating:
    response = pql_service.select(statement.ToStatement())
    column_types = ([column_type['labelName']
                     for column_type in response['columnTypes']])
    rows = response['rows']
    rows_length = len(rows)
    total_rows.extend(rows)

    if rows and rows_length > 0:
      # Get the earliest change ID in the result set.
      last_row = rows[-1]
      last_id = last_row['values'][0]['value']
github googleads / googleads-python-lib / examples / dfp / v201702 / user_service / deactivate_users.py View on Github external
def main(client, user_id):
  # Initialize appropriate service.
  user_service = client.GetService('UserService', version='v201702')

  # Create query.
  values = [{
      'key': 'userId',
      'value': {
          'xsi_type': 'NumberValue',
          'value': user_id
      }
  }]
  query = 'WHERE id = :userId'

  # Create a filter statement.
  statement = dfp.FilterStatement(query, values)

  # Get users by statement.
  response = user_service.getUsersByStatement(statement.ToStatement())
  users = response['results'] if 'results' in response else []

  for user in users:
    print ('User with id "%s", email "%s", and status "%s" will be '
           'deactivated.'
           % (user['id'], user['email'],
              {'true': 'ACTIVE', 'false': 'INACTIVE'}[user['isActive']]))
  print 'Number of users to be deactivated: %s' % len(users)

  # Perform action.
  result = user_service.performUserAction({'xsi_type': 'DeactivateUsers'},
                                          statement.ToStatement())
github googleads / googleads-python-lib / examples / dfp / v201802 / forecast_service / get_availability_forecast_for_line_item.py View on Github external
available_percent = 0

  contending_line_items = getattr(forecast, 'contentingLineItems', [])

  # Display results.
  print '%s %s matched.' % (matched, forecast['unitType'].lower())
  print '%s%% %s available.' % (available_percent, forecast['unitType'].lower())
  print '%d contending line items.' % len(contending_line_items)

  if 'possibleUnits' in forecast and matched:
    possible_percent = (long(forecast['possibleUnits'])/float(matched)) * 100.
    print '%s%% %s possible' % (possible_percent, forecast['unitType'].lower())

if __name__ == '__main__':
  # Initialize client object.
  dfp_client = dfp.DfpClient.LoadFromStorage()
  main(dfp_client, LINE_ITEM_ID)
github googleads / googleads-python-lib / examples / dfp / v201802 / creative_template_service / get_all_creative_templates.py View on Github external
def main(client):
  # Initialize appropriate service.
  creative_template_service = client.GetService(
      'CreativeTemplateService', version='v201802')

  # Create a statement to select creative templates.
  statement = dfp.StatementBuilder()

  # Retrieve a small amount of creative templates at a time, paging
  # through until all creative templates have been retrieved.
  while True:
    response = creative_template_service.getCreativeTemplatesByStatement(
        statement.ToStatement())
    if 'results' in response and len(response['results']):
      for creative_template in response['results']:
        # Print out some information for each creative template.
        print('Creative template with ID "%d" and name "%s" was found.\n' %
              (creative_template['id'], creative_template['name']))
      statement.offset += statement.limit
    else:
      break

  print '\nNumber of results found: %s' % response['totalResultSetSize']
github googleads / googleads-python-lib / examples / dfp / v201602 / content_service / get_content_by_category.py View on Github external
'xsi_type': 'NumberValue',
              'value': key_id
          }
      },
      {
          'key': 'category',
          'value': {
              'xsi_type': 'TextValue',
              'value': 'comedy'
          }
      }
  ]
  category_filter_query = ('WHERE customTargetingKeyId = '
                           ':contentBrowseCustomTargetingKeyId and name = '
                           ':category')
  category_filter_statement = dfp.FilterStatement(
      category_filter_query, values, 1)

  # Get categories matching the filter statement.
  response = custom_targeting_service.getCustomTargetingValuesByStatement(
      category_filter_statement.ToStatement())

  # Get the custom targeting value ID for the comedy category.
  if 'results' in response:
    category_custom_targeting_value_id = (response['results']['id'])

    # Create a statement to select the active content.
    content_values = [
        {
            'key': 'status',
            'value': {
                'xsi_type': 'TextValue',
github googleads / googleads-python-lib / examples / dfp / v201702 / suggested_ad_unit_service / approve_all_suggested_ad_units.py View on Github external
# Initialize appropriate service.
  suggested_ad_unit_service = client.GetService(
      'SuggestedAdUnitService', version='v201702')

  values = [{
      'key': 'numRequests',
      'value': {
          'xsi_type': 'NumberValue',
          'value': THRESHOLD_NUMBER_OF_REQUESTS
      }
  }]

  query = 'WHERE numRequests > :numRequests'

  # Create a filter statement.
  statement = dfp.FilterStatement(query, values)
  num_approved_suggested_ad_units = 0

  # Get suggested ad units by statement.
  while True:
    response = suggested_ad_unit_service.getSuggestedAdUnitsByStatement(
        statement.ToStatement())
    if 'results' in response:
      # Print suggested ad units that will be approved.
      for suggested_ad_unit in response['results']:
        print ('Suggested ad unit with id "%s", and number of requests "%s"'
               ' will be approved.' % (suggested_ad_unit['id'],
                                       suggested_ad_unit['numRequests']))

      # Approve suggested ad units.
      result = suggested_ad_unit_service.performSuggestedAdUnitAction(
          {'xsi_type': 'ApproveSuggestedAdUnits'},
github googleads / googleads-python-lib / examples / dfp / v201705 / user_service / get_all_users.py View on Github external
response = user_service.getUsersByStatement(statement.ToStatement())
    if 'results' in response:
      for user in response['results']:
        # Print out some information for each user.
        print('User with ID "%d" and name "%s" was found.\n' % (user['id'],
                                                                user['name']))
      statement.offset += statement.limit
    else:
      break

  print '\nNumber of results found: %s' % response['totalResultSetSize']


if __name__ == '__main__':
  # Initialize client object.
  dfp_client = dfp.DfpClient.LoadFromStorage()
  main(dfp_client)
github googleads / googleads-python-lib / examples / dfp / v201705 / workflow_request_service / get_workflow_approval_requests.py View on Github external
# Create a statement to select workflow requests.
  statement = dfp.FilterStatement(query, values)

  # Retrieve a small amount of workflow requests at a time, paging
  # through until all workflow requests have been retrieved.
  while True:
    response = workflow_request_service.getWorkflowRequestsByStatement(
        statement.ToStatement())
    if 'results' in response:
      for workflow_request in response['results']:
        # Print out some information for each workflow request.
        print('Workflow request with ID "%d", entity type "%s", and entity ID '
              '"%d" was found.\n' % (workflow_request['id'],
                                     workflow_request['entityType'],
                                     workflow_request['entityId']))
      statement.offset += dfp.SUGGESTED_PAGE_LIMIT
    else:
      break

  print '\nNumber of results found: %s' % response['totalResultSetSize']