def main(argv):
	sample_utils.process_flags(argv)

	# Authenticate and construct service.
	service = sample_utils.initialize_service()

	# Try to make a request to the API. Print the results or handle errors.
	try:
		# Limited to seven dimensions, so excluding ga:date since searching over one date
		#   at a time, anyway...
		metrics = 'ga:visitors'
		dimensions = 'ga:pagePath,ga:hour,ga:city,ga:region,ga:country,ga:latitude,ga:longitude'
		start_date_str = '2013-04-01'
		end_date_str = '2013-04-03'
		start_date = datetime.strptime(start_date_str, '%Y-%m-%d')
		end_date = datetime.strptime(end_date_str, '%Y-%m-%d')
		date_delta = end_date - start_date
		delta_days = date_delta.days + 1
		one_day = timedelta(days = 1)
		
		if delta_days > 0:
			for dd in range(delta_days):
				date = start_date + dd*one_day
				date_str = date.strftime('%Y-%m-%d')
				results = get_api_query(service, date_str, metrics, dimensions).execute()
				
				# print_results(results)
				rows_to_mongo(results, date_str)
			

	except TypeError, error:
		# Handle errors in constructing a query.
		print ('There was an error in constructing your query : %s' % error)
Example #2
0
def main(argv):
    # Process flags and read their values.
    sample_utils.process_flags(argv)
    ad_client_id = gflags.FLAGS.ad_client_id

    # Authenticate and construct service.
    service = sample_utils.initialize_service()

    try:
        # Retrieve URL channel list in pages and display data as we receive it.
        request = service.urlchannels().list(adClientId=ad_client_id,
                                             maxResults=MAX_PAGE_SIZE)

        while request is not None:
            result = request.execute()
            custom_channels = result['items']

            url_channels = result['items']
            for url_channel in url_channels:
                print('URL channel with URL pattern "%s" was found.' %
                      url_channel['urlPattern'])

            request = service.customchannels().list_next(request, result)

    except AccessTokenRefreshError:
        print(
            'The credentials have been revoked or expired, please re-run the '
            'application to re-authorize')
Example #3
0
def main(argv):
  # Process flags and read their values.
  sample_utils.process_flags(argv)
  ad_client_id = gflags.FLAGS.ad_client_id

  # Authenticate and construct service.
  service = sample_utils.initialize_service()

  try:
    # Retrieve report.
    result = service.reports().generate(
        startDate='2011-01-01', endDate='2011-08-31',
        filter=['AD_CLIENT_ID==' + ad_client_id],
        metric=['PAGE_VIEWS', 'AD_REQUESTS', 'AD_REQUESTS_COVERAGE',
                'CLICKS', 'AD_REQUESTS_CTR', 'COST_PER_CLICK',
                'AD_REQUESTS_RPM', 'EARNINGS'],
        dimension=['DATE'],
        sort=['+DATE']).execute()

    # Display headers.
    for header in result['headers']:
      print '%25s' % header['name'],
    print

    # Display results.
    for row in result['rows']:
      for column in row:
        print '%25s' % column,
      print

  except AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run the '
           'application to re-authorize')
Example #4
0
def main(argv):
    # Process flags and read their values.
    sample_utils.process_flags(argv)
    ad_client_id = gflags.FLAGS.ad_client_id

    # Authenticate and construct service.
    service = sample_utils.initialize_service()

    try:
        # Retrieve ad unit list in pages and display data as we receive it.
        request = service.adunits().list(adClientId=ad_client_id,
                                         maxResults=MAX_PAGE_SIZE)

        while request is not None:
            result = request.execute()
            ad_units = result['items']
            for ad_unit in ad_units:
                print(
                    'Ad unit with code "%s", name "%s" and status "%s" was found. '
                    % (ad_unit['code'], ad_unit['name'], ad_unit['status']))

            request = service.adunits().list_next(request, result)

    except AccessTokenRefreshError:
        print(
            'The credentials have been revoked or expired, please re-run the '
            'application to re-authorize')
Example #5
0
def main(argv):
    sample_utils.process_flags(argv)

    # Authenticate and construct service.
    service = sample_utils.initialize_service()

    try:
        # Retrieve ad client list in pages and display data as we receive it.
        request = service.adclients().list(maxResults=MAX_PAGE_SIZE)

        while request is not None:
            result = request.execute()
            ad_clients = result['items']
            for ad_client in ad_clients:
                print('Ad client for product "%s" with ID "%s" was found. ' %
                      (ad_client['productCode'], ad_client['id']))

                print('\tSupports reporting: %s' %
                      (ad_client['supportsReporting'] and 'Yes' or 'No'))

            request = service.adclients().list_next(request, result)

    except AccessTokenRefreshError:
        print(
            'The credentials have been revoked or expired, please re-run the '
            'application to re-authorize')
Example #6
0
def main(argv):
    sample_utils.process_flags(argv)

    # Authenticate and construct service.
    service = sample_utils.initialize_service()

    try:
        # Retrieve ad client list in pages and display data as we receive it.
        request = service.savedadstyles().list(maxResults=MAX_PAGE_SIZE)

        while request is not None:
            result = request.execute()
            saved_ad_styles = result['items']
            for saved_ad_style in saved_ad_styles:
                print(
                    'Saved ad style with ID "%s" and background color "#%s" was '
                    'found.' %
                    (saved_ad_style['id'],
                     saved_ad_style['adStyle']['colors']['background']))
                if ('corners' in saved_ad_style['adStyle']
                        and 'font' in saved_ad_style['adStyle']):
                    print('It has "%s" corners and a "%s" size font.' %
                          (saved_ad_style['adStyle']['corners'],
                           saved_ad_style['adStyle']['font']['size']))

            request = service.savedadstyles().list_next(request, result)

    except AccessTokenRefreshError:
        print(
            'The credentials have been revoked or expired, please re-run the '
            'application to re-authorize')
def main(argv):
  sample_utils.process_flags(argv)
  account_id = gflags.FLAGS.account_id
  adgroup_id = gflags.FLAGS.adgroup_id
  buyer_creative_id = gflags.FLAGS.buyer_creative_id
  pretty_printer = pprint.PrettyPrinter()

  # Authenticate and construct service.
  service = sample_utils.initialize_service()

  try:
    # Create a new creative to submit.
    creative_body = {
        'accountId': account_id,
        'adgroupId': adgroup_id,
        'buyerCreativeId': buyer_creative_id,
        'HTMLSnippet': ('<html><body><a href="http://www.google.com">'
                        'Hi there!</a></body></html>'),
        'clickThroughUrl': ['http://www.google.com'],
        'width': 300,
        'height': 250,
        'advertiserName': 'google'
        }
    creative = service.creatives().insert(body=creative_body).execute()
    # Print the response. If the creative has been already reviewed, its status
    # and categories will be included in the response.
    pretty_printer.pprint(creative)
  except AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run the '
           'application to re-authorize')
Example #8
0
def main(argv):
  sample_utils.process_flags(argv)

  # Authenticate and construct service.
  service = sample_utils.initialize_service()

  ad_client_id = 'INSERT_AD_CLIENT_ID_HERE'

  try:
    # Retrieve custom channel list in pages and display data as we receive it.
    request = service.customchannels().list(adClientId=ad_client_id,
        maxResults=MAX_PAGE_SIZE)

    while ( request != None ):
      result = request.execute()
      custom_channels = result['items']
      for custom_channel in custom_channels:
        print ('Custom channel with code "%s" and name "%s" was found. '
               % (custom_channel['code'], custom_channel['name']))

      request = service.customchannels().list_next(request, result)

  except AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run the '
           'application to re-authorize')
def main(argv):
  # Process flags and read their values.
  sample_utils.process_flags(argv)
  account_id = gflags.FLAGS.account_id
  ad_client_id = gflags.FLAGS.ad_client_id
  custom_channel_id = gflags.FLAGS.custom_channel_id

  # Authenticate and construct service.
  service = sample_utils.initialize_service()

  try:
    # Retrieve ad unit list in pages and display data as we receive it.
    request = service.accounts().customchannels().adunits().list(
        accountId=account_id, adClientId=ad_client_id,
        customChannelId=custom_channel_id, maxResults=MAX_PAGE_SIZE)

    while request is not None:
      result = request.execute()
      ad_units = result['items']
      for ad_unit in ad_units:
        print ('Ad unit with code "%s", name "%s" and status "%s" was found. ' %
               (ad_unit['code'], ad_unit['name'], ad_unit['status']))

      request = service.adunits().list_next(request, result)

  except AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run the '
           'application to re-authorize')
def main(argv):
    # Process flags and read their values.
    sample_utils.process_flags(argv)
    account_id = gflags.FLAGS.account_id

    # Authenticate and construct service.
    service = sample_utils.initialize_service()

    try:
        # Retrieve ad client list in pages and display data as we receive it.
        request = service.accounts().adclients().list(accountId=account_id, maxResults=MAX_PAGE_SIZE)

        while request is not None:
            result = request.execute()
            ad_clients = result["items"]
            for ad_client in ad_clients:
                print(
                    'Ad client for product "%s" with ID "%s" was found. ' % (ad_client["productCode"], ad_client["id"])
                )

                print("\tSupports reporting: %s" % (ad_client["supportsReporting"] and "Yes" or "No"))

            request = service.adclients().list_next(request, result)

    except AccessTokenRefreshError:
        print("The credentials have been revoked or expired, please re-run the " "application to re-authorize")
def main(argv):
  sample_utils.process_flags(argv)

  # Authenticate and construct service.
  service = sample_utils.initialize_service()

  try:
    # Retrieve ad client list in pages and display data as we receive it.
    request = service.savedadstyles().list(maxResults=MAX_PAGE_SIZE)

    while request is not None:
      result = request.execute()
      saved_ad_styles = result['items']
      for saved_ad_style in saved_ad_styles:
        print ('Saved ad style with ID "%s" and background color "#%s" was '
               'found.'
               % (saved_ad_style['id'],
                  saved_ad_style['adStyle']['colors']['background']))
        if ('corners' in saved_ad_style['adStyle']
            and 'font' in saved_ad_style['adStyle']):
          print ('It has "%s" corners and a "%s" size font.' %
                 (saved_ad_style['adStyle']['corners'],
                  saved_ad_style['adStyle']['font']['size']))

      request = service.savedadstyles().list_next(request, result)

  except AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run the '
           'application to re-authorize')
Example #12
0
def main(argv):
  sample_utils.process_flags(argv)

  # Authenticate and construct service.
  service = sample_utils.initialize_service()

  try:
    # Retrieve ad client list in pages and display data as we receive it.
    request = service.adclients().list(maxResults=MAX_PAGE_SIZE)

    while request is not None:
      result = request.execute()
      ad_clients = result['items']
      for ad_client in ad_clients:
        print ('Ad client for product "%s" with ID "%s" was found. '
               % (ad_client['productCode'], ad_client['id']))

        print ('\tSupports reporting: %s' %
               (ad_client['supportsReporting'] and 'Yes' or 'No'))

      request = service.adclients().list_next(request, result)

  except AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run the '
           'application to re-authorize')
def main(argv):
  sample_utils.process_flags(argv)

  # Authenticate and construct service.
  service = sample_utils.initialize_service()

  ad_client_id = 'INSERT_AD_CLIENT_ID_HERE'

  try:
    # Retrieve ad unit list in pages and display data as we receive it.
    request = service.adunits().list(adClientId=ad_client_id,
        maxResults=MAX_PAGE_SIZE)

    while ( request != None ):
      result = request.execute()
      ad_units = result['items']
      for ad_unit in ad_units:
        print ('Ad unit with code "%s", name "%s" and status "%s" was found. ' %
               (ad_unit['code'], ad_unit['name'], ad_unit['status']))

      request = service.adunits().list_next(request, result)

  except AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run the '
           'application to re-authorize')
Example #14
0
def main(argv):
  # Process flags and read their values.
  sample_utils.process_flags(argv)
  ad_client_id = gflags.FLAGS.ad_client_id

  # Authenticate and construct service.
  service = sample_utils.initialize_service()

  try:
    # Retrieve URL channel list in pages and display data as we receive it.
    request = service.urlchannels().list(adClientId=ad_client_id,
        maxResults=MAX_PAGE_SIZE)

    while request is not None:
      result = request.execute()
      custom_channels = result['items']

      url_channels = result['items']
      for url_channel in url_channels:
        print ('URL channel with URL pattern "%s" was found.'
               % url_channel['urlPattern'])

      request = service.customchannels().list_next(request, result)

  except AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run the '
           'application to re-authorize')
Example #15
0
def main(argv):
    sample_utils.process_flags(argv)

    # Authenticate and construct service.
    service = sample_utils.initialize_service()

    ad_client_id = 'INSERT_AD_CLIENT_ID_HERE'

    try:
        # Retrieve report in pages and display data as we receive it.
        start_index = 0
        rows_to_obtain = MAX_PAGE_SIZE
        while True:
            result = service.reports().generate(
                startDate='2011-01-01',
                endDate='2011-08-31',
                filter=['AD_CLIENT_ID==' + ad_client_id],
                metric=[
                    'PAGE_VIEWS', 'AD_REQUESTS', 'AD_REQUESTS_COVERAGE',
                    'CLICKS', 'AD_REQUESTS_CTR', 'COST_PER_CLICK',
                    'AD_REQUESTS_RPM', 'EARNINGS'
                ],
                dimension=['DATE'],
                sort=['+DATE'],
                startIndex=start_index,
                maxResults=rows_to_obtain).execute()

            # If this is the first page, display the headers.
            if start_index == 0:
                for header in result['headers']:
                    print '%25s' % header['name'],
                print

            # Display results for this page.
            for row in result['rows']:
                for column in row:
                    print '%25s' % column,
                print

            start_index += len(result['rows'])

            # Check to see if we're going to go above the limit and get as many
            # results as we can.
            if start_index + MAX_PAGE_SIZE > ROW_LIMIT:
                rows_to_obtain = ROW_LIMIT - start_index
                if rows_to_obtain <= 0:
                    break

            if (start_index >= int(result['totalMatchedRows'])):
                break

    except AccessTokenRefreshError:
        print(
            'The credentials have been revoked or expired, please re-run the '
            'application to re-authorize')
Example #16
0
def main(argv):
    sample_utils.process_flags(argv)

    # Authenticate and construct service.
    service = sample_utils.initialize_service()

    # Traverse the Management hiearchy and print results or handle errors.
    try:
        traverse_hiearchy(service)

    except TypeError, error:
        # Handle errors in constructing a query.
        print('There was an error in constructing your query : %s' % error)
def main(argv):
  sample_utils.process_flags(argv)

  # Authenticate and construct service.
  service = sample_utils.initialize_service()

  # Traverse the Management hiearchy and print results or handle errors.
  try:
    traverse_hiearchy(service)

  except TypeError, error:
    # Handle errors in constructing a query.
    print ('There was an error in constructing your query : %s' % error)
def main(argv):
  sample_utils.process_flags(argv)

  # Authenticate and construct service.
  service = sample_utils.initialize_service()

  ad_client_id = 'INSERT_AD_CLIENT_ID_HERE'

  try:
    # Retrieve report in pages and display data as we receive it.
    start_index = 0
    rows_to_obtain = MAX_PAGE_SIZE
    while True:
      result = service.reports().generate(
          startDate='2011-01-01', endDate='2011-08-31',
          filter=['AD_CLIENT_ID==' + ad_client_id],
          metric=['PAGE_VIEWS', 'AD_REQUESTS', 'AD_REQUESTS_COVERAGE',
                  'CLICKS', 'AD_REQUESTS_CTR', 'COST_PER_CLICK',
                  'AD_REQUESTS_RPM', 'EARNINGS'],
          dimension=['DATE'],
          sort=['+DATE'],
          startIndex=start_index,
          maxResults=rows_to_obtain).execute()

      # If this is the first page, display the headers.
      if start_index == 0:
        for header in result['headers']:
          print '%25s' % header['name'],
        print

      # Display results for this page.
      for row in result['rows']:
        for column in row:
          print '%25s' % column,
        print

      start_index += len(result['rows'])

      # Check to see if we're going to go above the limit and get as many
      # results as we can.
      if start_index + MAX_PAGE_SIZE > ROW_LIMIT:
        rows_to_obtain = ROW_LIMIT - start_index
        if rows_to_obtain <= 0:
          break

      if (start_index >= int(result['totalMatchedRows'])):
        break

  except AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run the '
           'application to re-authorize')
Example #19
0
def main(argv):
    sample_utils.process_flags(argv)

    # Authenticate and construct service.
    service = sample_utils.initialize_service()

    # Try to make a request to the API. Print the results or handle errors.
    try:
        results = get_api_query(service).execute()
        print_results(results)

    except TypeError, error:
        # Handle errors in constructing a query.
        print('There was an error in constructing your query : %s' % error)
def main(argv):
  sample_utils.process_flags(argv)
  pretty_printer = pprint.PrettyPrinter()

  # Authenticate and construct service
  service = sample_utils.initialize_service()

  try:
    # Retrieve account list and display data as received
    result = service.accounts().list().execute()
    pretty_printer.pprint(result)
  except AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run the '
           'application to re-authorize')
Example #21
0
def main(argv):
  sample_utils.process_flags(argv)

  # Authenticate and construct service.
  service = sample_utils.initialize_service()

  # Try to make a request to the API. Print the results or handle errors.
  try:
    results = get_api_query(service).execute()
    print_results(results)

  except TypeError, error:
    # Handle errors in constructing a query.
    print ('There was an error in constructing your query : %s' % error)
def main(argv):
    sample_utils.process_flags(argv)
    pretty_printer = pprint.PrettyPrinter()

    # Authenticate and construct service
    service = sample_utils.initialize_service()

    try:
        # Retrieve account list and display data as received
        result = service.accounts().list().execute()
        pretty_printer.pprint(result)
    except AccessTokenRefreshError:
        print(
            'The credentials have been revoked or expired, please re-run the '
            'application to re-authorize')
def main(argv):
    # Process flags and read their values.
    sample_utils.process_flags(argv)
    account_id = gflags.FLAGS.account_id
    ad_client_id = gflags.FLAGS.ad_client_id
    ad_unit_id = gflags.FLAGS.ad_unit_id

    # Authenticate and construct service.
    service = sample_utils.initialize_service()

    try:
        # Retrieve custom channel list in pages and display data as we receive it.
        request = service.accounts().adunits().customchannels().list(
            accountId=account_id,
            adClientId=ad_client_id,
            adUnitId=ad_unit_id,
            maxResults=MAX_PAGE_SIZE)

        while request is not None:
            result = request.execute()
            custom_channels = result['items']
            for custom_channel in custom_channels:
                print(
                    'Custom channel with code "%s" and name "%s" was found. ' %
                    (custom_channel['code'], custom_channel['name']))

                if 'targetingInfo' in custom_channel:
                    print '  Targeting info:'
                    targeting_info = custom_channel['targetingInfo']
                    if 'adsAppearOn' in targeting_info:
                        print '    Ads appear on: %s' % targeting_info[
                            'adsAppearOn']
                    if 'location' in targeting_info:
                        print '    Location: %s' % targeting_info['location']
                    if 'description' in targeting_info:
                        print '    Description: %s' % targeting_info[
                            'description']
                    if 'siteLanguage' in targeting_info:
                        print '    Site language: %s' % targeting_info[
                            'siteLanguage']

            request = service.customchannels().list_next(request, result)

    except AccessTokenRefreshError:
        print(
            'The credentials have been revoked or expired, please re-run the '
            'application to re-authorize')
def main(argv):
    sample_utils.process_flags(argv)

    # Authenticate and construct service.
    service = sample_utils.initialize_service()

    ad_client_id = "INSERT_AD_CLIENT_ID_HERE"

    try:
        # Retrieve report.
        result = (
            service.reports()
            .generate(
                startDate="2011-01-01",
                endDate="2011-08-31",
                filter=["AD_CLIENT_ID==" + ad_client_id],
                metric=[
                    "PAGE_VIEWS",
                    "AD_REQUESTS",
                    "AD_REQUESTS_COVERAGE",
                    "CLICKS",
                    "AD_REQUESTS_CTR",
                    "COST_PER_CLICK",
                    "AD_REQUESTS_RPM",
                    "EARNINGS",
                ],
                dimension=["DATE"],
                sort=["+DATE"],
            )
            .execute()
        )

        # Display headers.
        for header in result["headers"]:
            print "%25s" % header["name"],
        print

        # Display results.
        for row in result["rows"]:
            for column in row:
                print "%25s" % column,
            print

    except AccessTokenRefreshError:
        print ("The credentials have been revoked or expired, please re-run the " "application to re-authorize")
Example #25
0
def main(argv):
    sample_utils.process_flags(argv)

    # Authenticate and construct service.
    service = sample_utils.initialize_service()

    # Try to make a request to the API. Print the results or handle errors.
    try:
        first_profile_id = get_first_profile_id(service)
        if not first_profile_id:
            print 'Could not find a valid profile for this user.'
        else:
            results = get_top_keywords(service, first_profile_id)
            print_results(results)

    except TypeError, error:
        # Handle errors in constructing a query.
        print('There was an error in constructing your query : %s' % error)
def main(argv):
  sample_utils.process_flags(argv)

  # Authenticate and construct service.
  service = sample_utils.initialize_service()

  # Try to make a request to the API. Print the results or handle errors.
  try:
    first_profile_id = get_first_profile_id(service)
    if not first_profile_id:
      print 'Could not find a valid profile for this user.'
    else:
      results = get_top_keywords(service, first_profile_id)
      print_results(results)

  except TypeError, error:
    # Handle errors in constructing a query.
    print ('There was an error in constructing your query : %s' % error)
Example #27
0
def main(argv):
  # Process flags and read their values.
  sample_utils.process_flags(argv)
  account_id = gflags.FLAGS.account_id

  # Authenticate and construct service.
  service = sample_utils.initialize_service()

  try:
    # Retrieve account.
    request = service.accounts().get(accountId=account_id, tree=True)
    account = request.execute()

    if account:
      display_tree(account)

  except AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run the '
           'application to re-authorize')
def main(argv):
  sample_utils.process_flags(argv)
  pretty_printer = pprint.PrettyPrinter()

  # Authenticate and construct service.
  service = sample_utils.initialize_service()

  try:
    # Retrieve direct deals and display them as received if any.
    result = service.directDeals().list().execute()
    if 'direct_deals' in result:
      deals = result['direct_deals']
      for deal in deals:
        pretty_printer.pprint(deal)
    else:
      print 'No direct deals found'
  except AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run the '
           'application to re-authorize')
def main(argv):
	sample_utils.process_flags(argv)

	# Authenticate and construct service.
	service = sample_utils.initialize_service()

	# Try to make a request to the API. Print the results or handle errors.
	try:
		# The table ID is used to identify from which Google Anlaytics profile
		# to retrieve data. This ID is in the format ga:xxxx where xxxx is the
		# profile ID.
		table_ids = {'search':'ga:47958423', 'summon':'ga:53681003'}

		# Limited to seven dimensions, so excluding ga:date since searching over one date
		#		at a time, anyway...
		metrics='ga:visitors'
		dimensions='ga:searchKeyword,ga:hour,ga:city,ga:region,ga:country,ga:longitude,ga:latitude'
		# start_date_str = '2011-07-06'
		# end_date_str = '2012-03-20'
		start_date_str = '2012-04-19'
		end_date_str = '2012-09-25'
		start_date = datetime.strptime(start_date_str, '%Y-%m-%d')
		end_date = datetime.strptime(end_date_str, '%Y-%m-%d')
		date_delta = end_date - start_date
		delta_days = date_delta.days + 1
		one_day = timedelta(days = 1)
		
		if delta_days > 0:
			# for site_name,table_id in [('search','ga:47958423')]:
			for site_name,table_id in table_ids.items():
				for dd in range(delta_days):
					date = start_date + dd*one_day
					date_str = date.strftime('%Y-%m-%d')
					results = get_api_query(service, table_id, date_str, metrics, dimensions).execute()
					
					print_results(results)
					rows_to_mongo(results, site_name, date_str)
			

	except TypeError, error:
		# Handle errors in constructing a query.
		print ('There was an error in constructing your query : %s' % error)
Example #30
0
def main(argv):
    # Process flags and read their values.
    sample_utils.process_flags(argv)
    account_id = gflags.FLAGS.account_id

    # Authenticate and construct service.
    service = sample_utils.initialize_service()

    try:
        # Retrieve account.
        request = service.accounts().get(accountId=account_id, tree=True)
        account = request.execute()

        if account:
            display_tree(account)

    except AccessTokenRefreshError:
        print(
            'The credentials have been revoked or expired, please re-run the '
            'application to re-authorize')
Example #31
0
def main(argv):
    sample_utils.process_flags(argv)
    pretty_printer = pprint.PrettyPrinter()

    # Authenticate and construct service.
    service = sample_utils.initialize_service()

    try:
        # Retrieve direct deals and display them as received if any.
        result = service.directDeals().list().execute()
        if 'direct_deals' in result:
            deals = result['direct_deals']
            for deal in deals:
                pretty_printer.pprint(deal)
        else:
            print 'No direct deals found'
    except AccessTokenRefreshError:
        print(
            'The credentials have been revoked or expired, please re-run the '
            'application to re-authorize')
def main(argv):
  # Process flags and read their values.
  sample_utils.process_flags(argv)
  ad_client_id = gflags.FLAGS.ad_client_id
  saved_report_id = gflags.FLAGS.report_id

  # Authenticate and construct service.
  service = sample_utils.initialize_service()

  try:
    # Retrieve report.
    if saved_report_id:
      result = service.reports().saved().generate(
        savedReportId=saved_report_id).execute()
    elif ad_client_id:
      result = service.reports().generate(
          startDate='2011-01-01', endDate='2011-08-31',
          filter=['AD_CLIENT_ID==' + ad_client_id],
          metric=['PAGE_VIEWS', 'AD_REQUESTS', 'AD_REQUESTS_COVERAGE',
                  'CLICKS', 'AD_REQUESTS_CTR', 'COST_PER_CLICK',
                  'AD_REQUESTS_RPM', 'EARNINGS'],
          dimension=['DATE'],
          sort=['+DATE']).execute()
    else:
      print ('Specify ad client id or saved report id!\nUsage: %s ARGS\\n%s'
             % (sys.argv[0], gflags.FLAGS))
      sys.exit(1)
    # Display headers.
    for header in result['headers']:
      print '%25s' % header['name'],
    print

    # Display results.
    for row in result['rows']:
      for column in row:
        print '%25s' % column,
      print

  except AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run the '
           'application to re-authorize')
Example #33
0
def main(argv):
  sample_utils.process_flags(argv)
  account_id = gflags.FLAGS.account_id
  adgroup_id = gflags.FLAGS.adgroup_id
  buyer_creative_id = gflags.FLAGS.buyer_creative_id
  pretty_printer = pprint.PrettyPrinter()

  # Authenticate and construct service.
  service = sample_utils.initialize_service()

  try:
    # Construct the request.
    request = service.creatives().get(accountId=account_id,
                                      adgroupId=adgroup_id,
                                      buyerCreativeId=buyer_creative_id)

    # Execute request and print response.
    pretty_printer.pprint(request.execute())
  except AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run the '
           'application to re-authorize')
Example #34
0
def main(argv):
  sample_utils.process_flags(argv)
  account_id = gflags.FLAGS.account_id
  cookie_matching_url = gflags.FLAGS.cookie_matching_url
  pretty_printer = pprint.PrettyPrinter()

  # Authenticate and construct service.
  service = sample_utils.initialize_service()

  try:
    # Account information to be updated.
    account_body = {
        'accountId': account_id,
        'cookieMatchingUrl': cookie_matching_url
        }
    account = service.accounts().patch(id=account_id,
                                       body=account_body).execute()
    pretty_printer.pprint(account)
  except AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run the '
           'application to re-authorize')
def main(argv):
  # Process flags and read their values.
  sample_utils.process_flags(argv)
  account_id = gflags.FLAGS.account_id
  ad_client_id = gflags.FLAGS.ad_client_id
  ad_unit_id = gflags.FLAGS.ad_unit_id

  # Authenticate and construct service.
  service = sample_utils.initialize_service()

  try:
    # Retrieve custom channel list in pages and display data as we receive it.
    request = service.accounts().adunits().customchannels().list(
        accountId=account_id, adClientId=ad_client_id, adUnitId=ad_unit_id,
        maxResults=MAX_PAGE_SIZE)

    while request is not None:
      result = request.execute()
      custom_channels = result['items']
      for custom_channel in custom_channels:
        print ('Custom channel with code "%s" and name "%s" was found. '
               % (custom_channel['code'], custom_channel['name']))

        if 'targetingInfo' in custom_channel:
          print '  Targeting info:'
          targeting_info = custom_channel['targetingInfo']
          if 'adsAppearOn' in targeting_info:
            print '    Ads appear on: %s' % targeting_info['adsAppearOn']
          if 'location' in targeting_info:
            print '    Location: %s' % targeting_info['location']
          if 'description' in targeting_info:
            print '    Description: %s' % targeting_info['description']
          if 'siteLanguage' in targeting_info:
            print '    Site language: %s' % targeting_info['siteLanguage']

      request = service.customchannels().list_next(request, result)

  except AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run the '
           'application to re-authorize')
Example #36
0
def main(argv):
    sample_utils.process_flags(argv)
    account_id = gflags.FLAGS.account_id
    cookie_matching_url = gflags.FLAGS.cookie_matching_url
    pretty_printer = pprint.PrettyPrinter()

    # Authenticate and construct service.
    service = sample_utils.initialize_service()

    try:
        # Account information to be updated.
        account_body = {
            'accountId': account_id,
            'cookieMatchingUrl': cookie_matching_url
        }
        account = service.accounts().patch(id=account_id,
                                           body=account_body).execute()
        pretty_printer.pprint(account)
    except AccessTokenRefreshError:
        print(
            'The credentials have been revoked or expired, please re-run the '
            'application to re-authorize')
def main(argv):
  sample_utils.process_flags(argv)

  # Authenticate and construct service.
  service = sample_utils.initialize_service()

  try:
    # Retrieve ad client list in pages and display data as we receive it.
    request = service.reports().saved().list(maxResults=MAX_PAGE_SIZE)

    while request is not None:
      result = request.execute()
      saved_reports = result['items']
      for saved_report in saved_reports:
        print ('Saved ad style with ID "%s" and name "%s" was found.'
               % (saved_report['id'], saved_report['name']))

      request = service.reports().saved().list_next(request, result)

  except AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run the '
           'application to re-authorize')
def main(argv):
    sample_utils.process_flags(argv)

    # Authenticate and construct service.
    service = sample_utils.initialize_service()

    try:
        # Retrieve ad client list in pages and display data as we receive it.
        request = service.reports().saved().list(maxResults=MAX_PAGE_SIZE)

        while request is not None:
            result = request.execute()
            saved_reports = result['items']
            for saved_report in saved_reports:
                print('Saved ad style with ID "%s" and name "%s" was found.' %
                      (saved_report['id'], saved_report['name']))

            request = service.reports().saved().list_next(request, result)

    except AccessTokenRefreshError:
        print(
            'The credentials have been revoked or expired, please re-run the '
            'application to re-authorize')
Example #39
0
def main(argv):
    sample_utils.process_flags(argv)
    account_id = gflags.FLAGS.account_id
    adgroup_id = gflags.FLAGS.adgroup_id
    buyer_creative_id = gflags.FLAGS.buyer_creative_id
    pretty_printer = pprint.PrettyPrinter()

    # Authenticate and construct service.
    service = sample_utils.initialize_service()

    try:
        # Create a new creative to submit.
        creative_body = {
            'accountId':
            account_id,
            'adgroupId':
            adgroup_id,
            'buyerCreativeId':
            buyer_creative_id,
            'HTMLSnippet': ('<html><body><a href="http://www.google.com">'
                            'Hi there!</a></body></html>'),
            'clickThroughUrl': ['http://www.google.com'],
            'width':
            300,
            'height':
            250,
            'advertiserName':
            'google'
        }
        creative = service.creatives().insert(body=creative_body).execute()
        # Print the response. If the creative has been already reviewed, its status
        # and categories will be included in the response.
        pretty_printer.pprint(creative)
    except AccessTokenRefreshError:
        print(
            'The credentials have been revoked or expired, please re-run the '
            'application to re-authorize')