blob: ddc967ae54dcfabf0b1e7462f382267e8741a525 [file] [log] [blame]
Joe Gregorio093d9bf2011-09-08 16:09:55 -04001#!/usr/bin/python2.4
2# -*- coding: utf-8 -*-
3#
4# Copyright (C) 2011 Google Inc.
5
6"""Sample for retrieving credit-card offers from GAN."""
7
8__author__ = 'leadpipe@google.com (Luke Blanshard)'
9
10import gflags
11import httplib2
12import json
13import logging
14import os
15import stat
16import sys
17
18from django.conf import settings
19from django.template import Template, Context
20from django.template.loader import get_template
21
22from apiclient.discovery import build
23from oauth2client.file import Storage
leadpipe@wpgntav-ubiq70.hot.corp.google.combba48982011-11-02 16:27:24 -050024from oauth2client.client import AccessTokenRefreshError
25from oauth2client.client import flow_from_clientsecrets
Joe Gregorio093d9bf2011-09-08 16:09:55 -040026from oauth2client.tools import run
27
28settings.configure(DEBUG=True, TEMPLATE_DEBUG=True,
29 TEMPLATE_DIRS=('.'))
30
31
32FLAGS = gflags.FLAGS
33
leadpipe@wpgntav-ubiq70.hot.corp.google.combba48982011-11-02 16:27:24 -050034# CLIENT_SECRETS, name of a file containing the OAuth 2.0 information for this
35# application, including client_id and client_secret, which are found
36# on the API Access tab on the Google APIs
37# Console <http://code.google.com/apis/console>
38CLIENT_SECRETS = '../client_secrets.json'
39
40# Helpful message to display in the browser if the CLIENT_SECRETS file
41# is missing.
42MISSING_CLIENT_SECRETS_MESSAGE = """
43WARNING: Please configure OAuth 2.0
44
45To make this sample run you will need to populate the client_secrets.json file
46found at:
47
48 %s
49
50with information from the APIs Console <https://code.google.com/apis/console>.
51
52""" % os.path.join(os.path.dirname(__file__), CLIENT_SECRETS)
53
54# Set up a Flow object to be used if we need to authenticate.
55FLOW = flow_from_clientsecrets(CLIENT_SECRETS,
Joe Gregorio093d9bf2011-09-08 16:09:55 -040056 scope='https://www.googleapis.com/auth/gan.readonly',
leadpipe@wpgntav-ubiq70.hot.corp.google.combba48982011-11-02 16:27:24 -050057 message=MISSING_CLIENT_SECRETS_MESSAGE)
Joe Gregorio093d9bf2011-09-08 16:09:55 -040058
59# The gflags module makes defining command-line options easy for
60# applications. Run this program with the '--help' argument to see
61# all the flags that it understands.
62gflags.DEFINE_enum('logging_level', 'DEBUG',
63 ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
64 'Set the level of logging detail.')
65
66gflags.DEFINE_enum("output_type", 'STDOUT', ['BOTH', 'HTML', 'STDOUT'],
67 'Set how to output the results received from the API')
68
leadpipe@wpgntav-ubiq70.hot.corp.google.combba48982011-11-02 16:27:24 -050069gflags.DEFINE_string('credentials_filename', '../credentials.dat',
Joe Gregorio093d9bf2011-09-08 16:09:55 -040070 'File to store credentials in', short_name='cf')
71
leadpipe@wpgntav-ubiq70.hot.corp.google.combba48982011-11-02 16:27:24 -050072gflags.DEFINE_multistring('advertiser', [],
Joe Gregorio093d9bf2011-09-08 16:09:55 -040073 'If given, advertiser we should run as')
74
75
76def usage(argv):
77 print 'Usage: %s <publisher-id>\n%s' % (argv[0], FLAGS)
78 sys.exit(1)
79
80
81def main(argv):
82 # Let the gflags module process the command-line arguments
83 try:
84 argv = FLAGS(argv)
85 except gflags.FlagsError, e:
86 raise e
87 usage(argv)
88
89 if len(argv) != 2:
90 usage(argv)
91 publisher = argv[1]
92
93 # Set the logging according to the command-line flag
94 logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
95
96 # If the Credentials don't exist or are invalid run through the native client
97 # flow. The Storage object will ensure that if successful the good
98 # Credentials will get written back to a file.
99 storage = Storage(FLAGS.credentials_filename)
100 credentials = storage.get()
101 if credentials is None or credentials.invalid:
102 credentials = run(FLOW, storage)
103
104 # Create an httplib2.Http object to handle our HTTP requests and authorize it
105 # with our good Credentials.
106 http = httplib2.Http()
107 http = credentials.authorize(http)
108
109 service = build('gan', 'v1beta1', http=http)
110
111 ccOffers = service.ccOffers()
112
113 # Retrieve the relevant offers.
leadpipe@wpgntav-ubiq70.hot.corp.google.combba48982011-11-02 16:27:24 -0500114 request = ccOffers.list(publisher=publisher,
115 advertiser=FLAGS.advertiser,
116 projection='full')
117 response = request.execute()
118 response['publisher'] = publisher
Joe Gregorio093d9bf2011-09-08 16:09:55 -0400119
120 if FLAGS.output_type in ["BOTH", "HTML"]:
121 template = get_template('offers_template.html')
leadpipe@wpgntav-ubiq70.hot.corp.google.combba48982011-11-02 16:27:24 -0500122 context = Context(response)
Joe Gregorio093d9bf2011-09-08 16:09:55 -0400123
124 fname = '%s.html' % publisher
125 out = open(fname, 'w')
126 out.write(template.render(context).encode('UTF-8'))
127 os.fchmod(out.fileno(), stat.S_IROTH|stat.S_IRGRP|stat.S_IRUSR|stat.S_IWUSR)
128 out.close()
129
130 print 'Wrote %s' % fname
131
132 if FLAGS.output_type in ["BOTH", "STDOUT"]:
leadpipe@wpgntav-ubiq70.hot.corp.google.combba48982011-11-02 16:27:24 -0500133 print json.dumps(response, sort_keys=True, indent=4)
Joe Gregorio093d9bf2011-09-08 16:09:55 -0400134
135if __name__ == '__main__':
136 main(sys.argv)