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