googleads / googleads-python-lib

The Python client library for Google's Ads APIs
Apache License 2.0
682 stars 975 forks source link

Issues Downloading Reports as CSV Through Reporting API #458

Closed TAronee closed 4 years ago

TAronee commented 4 years ago

Hi,

I'm trying to pull a report through the Ad Manager API and save it as a csv file on my laptop using a service account. At the moment, I'm getting a report id, and also managing to save a csv file. However, the contents of the csv file are illegible. For example, below are the contents of my latest exported csv file:

‹ MÍ» ƒ0 DÑžoYÐîØkØ Å.(ò ŽÒR¥@ PDùÿ¸ŠÓ ÝÑÄu{îïõØ»8Þ Ž×gÛ»1.9Í 4/Óù6§œ§ë%7`p˾ G¢½°“JžÀj¦}%%H©D+ L†J}! ƒ¯4 Áฒ•G lø ¸Õ3þHÈy8 Í "ÑÖ

Below is the code I've written:

# Initialize client

from googleads import ad_manager

ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage('/Users/filePath/googleads.yaml')

# Set start and end dates for report

import datetime
from datetime import date

end_date = datetime.date.today()
start_date = end_date - datetime.timedelta(days=8)

# Create report job
statement = (ad_manager.StatementBuilder()
.Where('COUNTRY_CRITERIA_ID = 2554')
.Limit(None)
.Offset(None))

report_job = {
    'reportQuery': {
        'dimensions': ['DATE'],
        'columns': ['AD_SERVER_IMPRESSIONS', 'AD EXCHANGE REVENUE', 'AD_SERVER_AVERAGE_ECPM'],
        'statement': statement.ToStatement(),
        'dateRangeType': 'CUSTOM_DATE',
        'startDate': start_date,
        'endDate': end_date
    }
}

report_downloader = ad_manager_client.GetDataDownloader()

try:
    report_job_id = report_downloader.WaitForReport(report_job)
except errors.AdManagerError as e:
    print('Failed to generate Report. Error was: %s' % e)

# Download Report

import tempfile

print(report_job_id)
export_format= 'CSV_DUMP'
report_file = tempfile.NamedTemporaryFile(suffix='.csv', delete=False)

report_downloader.DownloadReportToFile(
    report_job_id, export_format, report_file
)
report_file.close()

print('Report job with id "%s" downloaded to :\n%s' % (
    report_job_id, report_file.name))

Thanks in advance for your help!

christopherseeley commented 4 years ago

Looks like the report might be gzipped, that's the default setting for DownloadReportToFile. You can change your extension to .csv.gz or disable gzip compression on the downloader.

TAronee commented 4 years ago

Thanks @christopherseeley. That did the trick :)