class DV360Reports:
def __init__(self, query_id, outputdirectory, cfg, reportWindow = 12):
self.cfg = cfg
self.arguments = self.get_arguments()
self.outputdir = outputdirectory
self.reportWindow = reportWindow
self.apiSecrets = cfg.path["bidManagerSecrets"]
#print(self.outputdir)
def get_arguments(self, argv = sys.argv, desc = __doc__, parents=None):
parent_parsers = [tools.argparser]
if parents:
parent_parsers.extend(parents)
parser = argparse.ArgumentParser(
description=desc,
formatter_class=argparse.RawDescriptionHelpFormatter,
parents=parent_parsers)
return parser.parse_args(argv[1:])
def setup(self, flags, secretsPath = None):
if secretsPath == None:
secretsPath = self.apiSecrets
API_NAME = 'doubleclickbidmanager'
API_VERSION = 'v1.1'
CREDENTIAL_STORE_FILE = API_NAME + '.dat'
credentials = self.load_application_default_credentials()
if credentials is None:
client_secrets = secretsPath
storage = oauthFile.Storage(CREDENTIAL_STORE_FILE)
credentials = self.load_user_credentials(client_secrets, storage, flags)
# Authorize HTTP object with the prepared credentials.
http = credentials.authorize(http=httplib2.Http())
# Construct and return a service object via the discovery service.
return discovery.build(API_NAME, API_VERSION, http=http)
def load_application_default_credentials(self):
API_SCOPES = ['https://www.googleapis.com/auth/doubleclickbidmanager']
try:
credentials = client.GoogleCredentials.get_application_default()
return credentials.create_scoped(API_SCOPES)
except client.ApplicationDefaultCredentialsError:
pass
def load_user_credentials(self,client_secrets, storage, flags):
API_SCOPES = ['https://www.googleapis.com/auth/doubleclickbidmanager']
flow = client.flow_from_clientsecrets(
client_secrets,
scope=API_SCOPES,
message=tools.message_if_missing(client_secrets))
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = tools.run_flow(flow, storage, flags)
return credentials
def performDownload(self, query_id, report_window = None, output_dir = None):
if report_window == None:
report_window = self.reportWindow
if report_window != None:
self.reportWindow = report_window
doubleclick_bid_manager = self.setup(self.arguments)
if output_dir != None:
self.outputdir = output_dir
if output_dir == None:
output_dir = self.outputdir
if query_id:
query = (
try:
if (self.is_in_report_window(query['metadata']['latestReportRunTimeMs'],
report_window)):
if not os.path.isabs(output_dir):
output_dir = os.path.expanduser(output_dir)
report_url = query['metadata']['googleCloudStoragePathForLatestReport']
output_file = '%s/%s.csv' % (output_dir, query['queryId'])
with open(output_file, 'wb') as output:
with closing(urlopen(report_url)) as url:
output.write(url.read())
return pd.read_csv(output_file,low_memory=False,encoding= 'unicode_escape')
else:
print("Comes under else")
print('No reports for queryId "%s" in the last %s hours.' %
(query['queryId'], report_window))
except KeyError:
print('No report found for queryId "%s".' % query_id)
else:
response = doubleclick_bid_manager.queries().listqueries().execute()
print('Id\t\tName')
if 'queries' in response:
self.print_queries(response)
# Then everything else
while 'nextPageToken' in response and response['nextPageToken']:
response = doubleclick_bid_manager.queries().listqueries(
pageToken=response['nextPageToken']).execute()
self.print_queries(response)
else:
print('No queries exist.')
return False
def print_queries(self, response):
for q in response['queries']:
print('%s\t%s' % (q['queryId'], q['metadata']['title']))
def is_in_report_window(self, run_time_ms, report_window):
report_time = datetime.fromtimestamp(int((run_time_ms)) / 1000)
earliest_time_in_range = datetime.now() - timedelta(hours=report_window)
return report_time > earliest_time_in_range
When I call performDownload, I get the error as mentioned above. Does anyone know what am I doing wrong? Good thing is that this same script works amazingly in my local system, but doesn't happen to run when running from google cloud platform instance.