2828"""
2929import argparse
3030import csv
31- import sys
3231import os
32+ import sys
3333
3434from google .ads .googleads .client import GoogleAdsClient
3535from google .ads .googleads .errors import GoogleAdsException
3939
4040
4141def main (client , customer_id , output_file , write_headers ):
42- """Writes rows returned from a search_stream request to a CSV file.
43- Args:
44- client: An initialized GoogleAdsClient instance.
45- customer_id (str): The client customer ID string.
46- output_file (str): Filename of the file to write the report data to.
47- write_headers (bool): From argparse, True if arg is provided.
48- """
49- file_dir = os .path .dirname (os .path .abspath (__file__ ))
50- file_path = os .path .join (file_dir , output_file )
51- ga_service = client .get_service ("GoogleAdsService" )
52-
53- query = """
42+ """Writes rows returned from a search_stream request to a CSV file.
43+
44+ Args:
45+ client: An initialized GoogleAdsClient instance.
46+ customer_id (str): The client customer ID string.
47+ output_file (str): Filename of the file to write the report data to.
48+ write_headers (bool): From argparse, True if arg is provided.
49+ """
50+ file_dir = os .path .dirname (os .path .abspath (__file__ ))
51+ file_path = os .path .join (file_dir , output_file )
52+ ga_service = client .get_service ("GoogleAdsService" )
53+
54+ query = """
5455 SELECT
5556 customer.descriptive_name,
5657 segments.date,
@@ -64,99 +65,103 @@ def main(client, customer_id, output_file, write_headers):
6465 ORDER BY metrics.impressions DESC
6566 LIMIT 25"""
6667
67- # Issues a search request using streaming.
68- search_request = client .get_type ("SearchGoogleAdsStreamRequest" )
69- search_request .customer_id = customer_id
70- search_request .query = query
71- stream = ga_service .search_stream (search_request )
72-
73- with open (file_path , "w" , newline = "" ) as f :
74- writer = csv .writer (f )
75-
76- # Define a list of headers for the first row.
77- headers = [
78- "Account" ,
79- "Date" ,
80- "Campaign" ,
81- "Impressions" ,
82- "Clicks" ,
83- "Cost" ,
84- ]
85-
86- # If the write_headers flag was passed, write header row to the CSV
87- if write_headers :
88- writer .writerow (headers )
89-
90- for batch in stream :
91- for row in batch .results :
92- # Use the CSV writer to write the individual GoogleAdsRow
93- # fields returned in the SearchGoogleAdsStreamResponse.
94- writer .writerow (
95- [
96- row .customer .descriptive_name ,
97- row .segments .date ,
98- row .campaign .name ,
99- row .metrics .impressions ,
100- row .metrics .clicks ,
101- row .metrics .cost_micros ,
102- ]
103- )
104-
105- print (f"Customer { customer_id } report written to { output_file } " )
68+ # Issues a search request using streaming.
69+ search_request = client .get_type ("SearchGoogleAdsStreamRequest" )
70+ search_request .customer_id = customer_id
71+ search_request .query = query
72+ stream = ga_service .search_stream (search_request )
73+
74+ with open (file_path , "w" , newline = "" ) as f :
75+ writer = csv .writer (f )
76+
77+ # Define a list of headers for the first row.
78+ headers = [
79+ "Account" ,
80+ "Date" ,
81+ "Campaign" ,
82+ "Impressions" ,
83+ "Clicks" ,
84+ "Cost" ,
85+ ]
86+
87+ # If the write_headers flag was passed, write header row to the CSV
88+ if write_headers :
89+ writer .writerow (headers )
90+
91+ for batch in stream :
92+ for row in batch .results :
93+ # Use the CSV writer to write the individual GoogleAdsRow
94+ # fields returned in the SearchGoogleAdsStreamResponse.
95+ writer .writerow ([
96+ row .customer .descriptive_name ,
97+ row .segments .date ,
98+ row .campaign .name ,
99+ row .metrics .impressions ,
100+ row .metrics .clicks ,
101+ row .metrics .cost_micros ,
102+ ])
103+
104+ print (f"Customer { customer_id } report written to { output_file } " )
106105
107106
108107if __name__ == "__main__" :
109- parser = argparse .ArgumentParser (
110- description = "Retrieves a campaign stats and writes to CSV file."
111- )
112- # The following argument(s) should be provided to run the example.
113- parser .add_argument (
114- "-c" ,
115- "--customer_id" ,
116- type = str ,
117- required = True ,
118- help = "The Google Ads customer ID of the account you would like to get "
119- "the report for to write to CSV." ,
120- )
121- parser .add_argument (
122- "-o" ,
123- "--output_file" ,
124- type = str ,
125- required = False ,
126- default = _DEFAULT_FILE_NAME ,
127- help = "Name of the local CSV file to save the report to. File will be "
128- "saved in the same directory as the script." ,
108+ parser = argparse .ArgumentParser (
109+ description = "Retrieves a campaign stats and writes to CSV file."
110+ )
111+ # The following argument(s) should be provided to run the example.
112+ parser .add_argument (
113+ "-c" ,
114+ "--customer_id" ,
115+ type = str ,
116+ required = True ,
117+ help = (
118+ "The Google Ads customer ID of the account you would like to get "
119+ "the report for to write to CSV."
120+ ),
121+ )
122+ parser .add_argument (
123+ "-o" ,
124+ "--output_file" ,
125+ type = str ,
126+ required = False ,
127+ default = _DEFAULT_FILE_NAME ,
128+ help = (
129+ "Name of the local CSV file to save the report to. File will be "
130+ "saved in the same directory as the script."
131+ ),
132+ )
133+ # Optional boolean argument for writing headers.
134+ parser .add_argument (
135+ "-w" ,
136+ "--write_headers" ,
137+ action = "store_true" ,
138+ help = (
139+ "Writes headers to the CSV file if argument is supplied. Simply "
140+ "add -w if you want the headers defined in the script to be "
141+ "added as the first row in the CSV file."
142+ ),
143+ )
144+ args = parser .parse_args ()
145+
146+ # GoogleAdsClient will read the google-ads.yaml configuration file in the
147+ # home directory if none is specified.
148+ googleads_client = GoogleAdsClient .load_from_storage (version = "v20" )
149+
150+ try :
151+ main (
152+ googleads_client ,
153+ args .customer_id ,
154+ args .output_file ,
155+ args .write_headers ,
129156 )
130- # Optional boolean argument for writing headers.
131- parser .add_argument (
132- "-w" ,
133- "--write_headers" ,
134- action = "store_true" ,
135- help = "Writes headers to the CSV file if argument is supplied. Simply "
136- "add -w if you want the headers defined in the script to be "
137- "added as the first row in the CSV file." ,
157+ except GoogleAdsException as ex :
158+ print (
159+ f'Request with ID "{ ex .request_id } " failed with status '
160+ f'"{ ex .error .code ().name } " and includes the following errors:'
138161 )
139- args = parser .parse_args ()
140-
141- # GoogleAdsClient will read the google-ads.yaml configuration file in the
142- # home directory if none is specified.
143- googleads_client = GoogleAdsClient .load_from_storage (version = "v19" )
144-
145- try :
146- main (
147- googleads_client ,
148- args .customer_id ,
149- args .output_file ,
150- args .write_headers ,
151- )
152- except GoogleAdsException as ex :
153- print (
154- f'Request with ID "{ ex .request_id } " failed with status '
155- f'"{ ex .error .code ().name } " and includes the following errors:'
156- )
157- for error in ex .failure .errors :
158- print (f'\t Error with message "{ error .message } ".' )
159- if error .location :
160- for field_path_element in error .location .field_path_elements :
161- print (f"\t \t On field: { field_path_element .field_name } " )
162- sys .exit (1 )
162+ for error in ex .failure .errors :
163+ print (f'\t Error with message "{ error .message } ".' )
164+ if error .location :
165+ for field_path_element in error .location .field_path_elements :
166+ print (f"\t \t On field: { field_path_element .field_name } " )
167+ sys .exit (1 )
0 commit comments