Created
October 21, 2015 16:11
-
-
Save wordmuncher/9379bcb4aae9530214d3 to your computer and use it in GitHub Desktop.
Stuff for connecting to Adwords
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
import StringIO | |
import sys | |
from googleads import adwords | |
from googleads import oauth2 | |
CLIENT_ID = 'xxx' | |
CLIENT_SECRET = 'xxx' | |
REFRESH_TOKEN = 'xxx' | |
DEVELOPER_TOKEN = 'xxx' | |
USER_AGENT = 'noodle.com:noodle-dashboard:V0.1' | |
CLIENT_CUSTOMER_ID = 'xxx' | |
# CLIENT_CUSTOMER_ID = 'xxx' | |
logging.basicConfig(level=logging.INFO) | |
logging.getLogger('suds.transport').setLevel(logging.DEBUG) | |
# Specify where to download the file here. | |
# PATH = '~/projects/report_download.csv' | |
# The chunk size used for the report download. | |
CHUNK_SIZE = 16 * 1024 | |
def main(client): | |
# Initialize appropriate service. | |
report_downloader = client.GetReportDownloader(version='v201509') | |
# Create report query. | |
report_query = ('SELECT CampaignId, CampaignName, ExternalCustomerId, ' | |
'Date, HourOfDay, Impressions, Clicks, Cost ' | |
'FROM CAMPAIGN_PERFORMANCE_REPORT ' | |
# 'WHERE Impressions > 0 ' | |
'DURING YESTERDAY') | |
print report_query | |
print report_downloader.DownloadReportAsStringWithAwql( | |
report_query, 'CSV', skip_report_header=False, skip_column_header=False, | |
skip_report_summary=False, include_zero_impressions=False) | |
# Retrieve the report stream and print it out | |
report_data = StringIO.StringIO() | |
stream_data = report_downloader.DownloadReportAsStreamWithAwql(report_query, | |
'CSV') | |
try: | |
while True: | |
chunk = stream_data.read(CHUNK_SIZE) | |
if not chunk: break | |
report_data.write(chunk.decode() if sys.version_info[0] == 3 | |
and getattr(report_data, 'mode', 'w') == 'w' else chunk) | |
print report_data.getvalue() | |
finally: | |
report_data.close() | |
stream_data.close() | |
if __name__ == '__main__': | |
# Initialize client object. | |
oauth2_client = oauth2.GoogleRefreshTokenClient( | |
CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN) | |
adwords_client = adwords.AdWordsClient( | |
DEVELOPER_TOKEN, oauth2_client, USER_AGENT, CLIENT_CUSTOMER_ID) | |
customer = adwords_client.GetService('CustomerService').get() | |
print 'You are logged in as customer: %s' % customer['customerId'] | |
main(adwords_client) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment