API DoubleClickBidManager данные не получены.
Я создал проект в Google Cloud, включил API DV360 и DoubleClick Bid Manager, создал идентификаторы и учетные данные клиента oAuth 2.0, а также загрузил секретный код клиента JSON, который я прикрепил к корню своего проекта. В моем коде Python я пытаюсь получить данные (любые данные) из метода query.create, а затем зацикливаться, пока статус отчета не станет ДОСТУПНЫМ, используя
import logging
import csv
import time
import urllib.request
import os
import pickle
from googleapiclient.errors import HttpError
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
API_VERSION = 'v2'
ADVERTISER_ID = '*****'
SCOPES = ['https://www.googleapis.com/auth/doubleclickbidmanager']
# Set up the credentials
creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'/Users/directory to root', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
# Build the doubleclickbidmanager API client
service = build('doubleclickbidmanager', API_VERSION, credentials=creds)
# Set up logging
logging.basicConfig(level=logging.DEBUG)
# Create a query
query_body = {
"metadata": {
"title": "Basic Report",
"dataRange": {
"range": "LAST_7_DAYS"
},
"format": "CSV"
},
"params": {
"type": "STANDARD",
"groupBys": ["FILTER_PARTNER"],
"metrics": ["METRIC_IMPRESSIONS"]
},
"schedule": {
"frequency": "ONE_TIME"
}
}
try:
# Run the query
query_create = service.queries().create(body=query_body).execute()
print(f'Query creation response: {query_create}')
query_id = query_create['queryId']
logging.debug(f'Query ID: {query_id}')
logging.debug("Query executed")
# Wait for the report to be generated
report_available = False
num_retries = 0
while not report_available and num_retries < 100:
try:
query = service.queries().get(queryId=query_id).execute()
print(f'Query data: {query}')
print(f'Query metadata: {query.get("metadata")}')
except Exception as e:
print('Error occurred: ', e)
if 'error' in query:
logging.error(f'Error in query: {query.get("error")}')
print(f'Query retrieval response: {query}')
logging.debug(f'Query status: {query["metadata"]}, query ID: {query["queryId"]}')
logging.debug(f'ReportStatus: {query.get("metadata", {}).get("status", {})}')
# Check if report is ready or has failed
state = query.get('metadata', {}).get('status', {}).get('state')
if state == 'DONE':
report_available = True
elif state == 'FAILED':
logging.error("Report generation failed.")
break
else:
logging.debug("Waiting 30 seconds before checking again")
time.sleep(30)
num_retries += 1
if not report_available:
logging.error('Report did not become available after 100 retries. Aborting.')
else:
# Get the Google Cloud Storage path for the report
google_cloud_storage_path = query.get('metadata', {}).get('googleCloudStoragePath', '')
if google_cloud_storage_path:
# Download the report as CSV
report_file_name = 'campaign_overview_report.csv'
urllib.request.urlretrieve(google_cloud_storage_path, report_file_name)
print("Report downloaded.")
else:
print("Google Cloud Storage path not found for the report.")
except Exception as ex:
print('Exception occurred during query execution: ', ex)
Почему мой статус отчета постоянно возвращается пустым? Я назначен «владельцем» проекта, поэтому разрешения не будут проблемой. Даже если данных нет, статус обязательно должен обновиться? Я делаю что-то неправильно?