Posts tagged with python

I've been trying to follow the examples and documentation for the python ad_manager library for the google ads API, but I haven't been able to complete a successful request. I currently have my developer token, client_id, client_secret, and refresh_token in my google ads YAML file, but I'm constantly getting the error "argument should be integer or bytes-like object, not 'str'" when calling the function WaitForReport following the example code below. I was wondering if anyone had any advice on how I could tackle this issue.

 import tempfile # Import appropriate modules from the client library. from googleads import ad_manager from googleads import errors def main(client):   # Initialize a DataDownloader.   report_downloader = client.GetDataDownloader(version='v202111')   # Create report job.   report_job = {       'reportQuery': {           'dimensions': ['COUNTRY_NAME', 'LINE_ITEM_ID', 'LINE_ITEM_NAME'],           'columns': ['UNIQUE_REACH_FREQUENCY', 'UNIQUE_REACH_IMPRESSIONS',                       'UNIQUE_REACH'],           'dateRangeType': 'REACH_LIFETIME'       }   }   try:     # Run the report and wait for it to finish.     report_job_id = report_downloader.WaitForReport(report_job)   except errors.AdManagerReportError as e:     print('Failed to generate report. Error was: %s' % e)   # Change to your preferred export format.   export_format = 'CSV_DUMP'   report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)   # Download report data.   report_downloader.DownloadReportToFile(       report_job_id, export_format, report_file)   report_file.close()   # Display results.   print('Report job with id "%s" downloaded to:\n%s' % (       report_job_id, report_file.name)) if __name__ == '__main__':   # Initialize client object.   ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()   main(ad_manager_client) 

Edit: Below is the stack trace:

Traceback (most recent call last):   File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/googleads/common.py", line 984, in MakeSoapRequest     return soap_service_method(   File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/zeep/proxy.py", line 46, in __call__     return self._proxy._binding.send(   File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/zeep/wsdl/bindings/soap.py", line 135, in send     return self.process_reply(client, operation_obj, response)   File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/zeep/wsdl/bindings/soap.py", line 229, in process_reply     return self.process_error(doc, operation)   File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/zeep/wsdl/bindings/soap.py", line 317, in process_error     raise Fault( zeep.exceptions.Fault: Unknown fault occured During handling of the above exception, another exception occurred: Traceback (most recent call last):   File "google_ads.py", line 72, in <module>     main(ad_manager_client)   File "google_ads.py", line 33, in main1     report_job_id = report_downloader.WaitForReport(report_job)   File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/googleads/ad_manager.py", line 784, in WaitForReport     report_job_id = service.runReportJob(report_job)['id']   File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/googleads/common.py", line 989, in MakeSoapRequest     underlying_exception = e.detail.find( TypeError: argument should be integer or bytes-like object, not 'str' 

I'm currently running a script locally to generate reports using GoogleAdsManager API. Prior running the script I've created new service account key in json format as the key type together with ~/googleads.yaml.

Here's the dev guide.

However, I wanted to schedule this script on (AWS Glue).

This is the sample script and the issue I currently faced is :

How do call this method ad_manager.AdManagerClient.LoadFromStorage() from aws? I've stored the credentials (JSON and YAML) in AWS Secrets Manager

from googleads import ad_manager, oauth2 import tempfile import _locale _locale._getdefaultlocale = (lambda *args: ['en_US', 'UTF-8']) ad_unit_id = XXXXXXXXXX def generate_ad_impressions(client):     # Initialize appropriate service.     report_service = client.GetService("ReportService",      version="v202108")     # Initialize a DataDownloader.     report_downloader = client.GetDataDownloader(version="v202108")     # Create statement object to filter for an order.     statement = (         ad_manager.StatementBuilder(version="v202108")         .Where("PARENT_AD_UNIT_ID = :id")         .WithBindVariable("id", mbns_aa_vod_ad_unit_id)         .Limit(None)  # No limit/offset for reports         .Offset(None)     )     report_job = {         "reportQuery": {         "dimensions": ["DATE", "HOUR"],         "columns": [             "AD_SERVER_IMPRESSIONS",         ],         "dateRangeType": "TODAY",         "startDate": {             "year": "2022",             "month": "1",             "day": "25"         },         "endDate": {             "year": "2022",             "month": "1",             "day": "25"         },         "statement": statement.ToStatement(),       }     }     try:         # Run the report and wait for it to finish.         report_job_id = report_downloader.WaitForReport(report_job)     except:         print("Failed to generate report.")         # Change to your preferred export format.         export_format = "CSV_DUMP"         # report_file =         tempfile.NamedTemporaryFile(suffix=".csv.gz",          delete=False)     with open('ad_unit_report.csv.gz', mode='wb') as report_file:         # Download report data.         report_downloader.DownloadReportToFile(report_job_id,          export_format, report_file)         report_file.close()     # Download report data.     downloaded_report =      report_downloader.DownloadReportToFile(report_job_id,      export_format, report_file)     report_file.close()     print('success!') if __name__ == '__main__':    ad_manager_client =     ad_manager.AdManagerClient.LoadFromStorage('path_to_yaml_file')    generate_ad_impressions(ad_manager_client) 

I want to deploy working python project in pycharm to aws lambda. The project is using google-ads library to get some report data from google ads.

I tried deploying lambda by importing complete project as a zip file by zipping all the folders/files inside the project and not the project folder itself. But i got the following error:

{ "errorMessage": "Unable to import module 'main': cannot import name 'cygrpc' from 'grpc._cython' (/var/task/grpc/_cython/__init__.py)", "errorType": "Runtime.ImportModuleError", "stackTrace": [] } 

Assuming that google-ads library is working and that something is wrong with grpc(btw google-ads includes grpcio and stuff on its own), i tried to create a layer for grpcio, cython, cygrpc but the error remains same.

I create projects/layers in aws lambda and they work. I dont know what i am doing wrong here.

Any help would be really appreciated!

versions: google-ads-14.1.0, python-3.9, grpcio-1.43.0

im trying to use get functions for reports under googleads.

#My code

from googleads import adwords from googleads import errors import time import datetime import os import sys if __name__ == '__main__':   ## initialize google adwords client object   adwords_client = adwords.AdWordsClient.LoadFromStorage("googleAds.yaml")   ## set your customer-ID   adwords_client.SetClientCustomerId('389204095687-xx.apps.googleusercontent.com')   report_downloader = adwords_client.GetReportDownloader(version='v9')   ## get CLICK_PERFORMANCE report for yesterday as an example   report_date = datetime.datetime.now()-datetime.timedelta(days=1)   report_date_string = report_date.strftime("%Y%m%d")   ## build the report query   report_query = (adwords.ReportQueryBuilder()       .Select('campaign.id','ad_group.id', 'metrics.impressions', 'metrics.clicks')       .From('ad_group')       .During(start_date=report_date_string,end_date=report_date_string)       .Build())   ## download the report as CSV into string   csv_report = report_downloader.DownloadReportWithAwql(       report_query, 'CSV', skip_report_header=True,       skip_column_header=True, skip_report_summary=True,       include_zero_impressions=False)    

But i receive the below traceback error-

   with open(path, 'rb') as handle: FileNotFoundError: [Errno 2] No such file or directory: 'googleAds.yaml' During handling of the above exception, another exception occurred: Traceback (most recent call last):   File "<ipython-input-5-d90ad0259074>", line 16, in <module>     adwords_client = adwords.AdWordsClient.LoadFromStorage("googleAds.yaml")   File "C:\Users\jj\AppData\Local\Continuum\anaconda3\lib\site-packages\googleads\adwords.py", line 193, in LoadFromStorage     cls._OPTIONAL_INIT_VALUES))   File "C:\Users\jj\AppData\Local\Continuum\anaconda3\lib\site-packages\googleads\common.py", line 247, in LoadFromStorage     'Given yaml file, %s, could not be opened.' % path) GoogleAdsValueError: Given yaml file, googleAds.yaml, could not be opened. 

I reviewed the documentation for Oath: https://github.com/googleads/googleads-python-lib/wiki/API-access-using-own-credentials-(installed-application-flow)#step-2---setting-up-the-client-library

but I already have all the credentials, i just dont know how to create the yml file and save it where python can detect it