blob: 05a42c0ca3acc7fe16a07e13461f5fb3440d338c [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 apiclient
11import gflags
12import httplib2
13import json
14import logging
15import os
16import stat
17import sys
18
19from django.conf import settings
20from django.template import Template, Context
21from django.template.loader import get_template
22
23from apiclient.discovery import build
24from oauth2client.file import Storage
25from oauth2client.client import OAuth2WebServerFlow
26from oauth2client.tools import run
27
28settings.configure(DEBUG=True, TEMPLATE_DEBUG=True,
29 TEMPLATE_DIRS=('.'))
30
31
32FLAGS = gflags.FLAGS
33
34# Set up a Flow object to be used if we need to authenticate. This
35# sample uses OAuth 2.0, and we set up the OAuth2WebServerFlow with
36# the information it needs to authenticate. Note that it is called
37# the Web Server Flow, but it can also handle the flow for native
38# applications <http://code.google.com/apis/accounts/docs/OAuth2.html#IA>
39# The client_id client_secret are copied from the API Access tab on
40# the Google APIs Console <http://code.google.com/apis/console>. When
41# creating credentials for this application be sure to choose an Application
42# type of "Installed application".
43FLOW = OAuth2WebServerFlow(
44 client_id='767567128246-ti2q06i1neqm5boe2m1pqdc2riivhk41.apps.googleusercontent.com',
45 client_secret='UtdXI8nKD2SEcQRLQDZPkGT9',
46 scope='https://www.googleapis.com/auth/gan.readonly',
47 user_agent='gan-events-sample/1.0')
48
49# The gflags module makes defining command-line options easy for
50# applications. Run this program with the '--help' argument to see
51# all the flags that it understands.
52gflags.DEFINE_enum('logging_level', 'DEBUG',
53 ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
54 'Set the level of logging detail.')
55
56gflags.DEFINE_enum("output_type", 'STDOUT', ['BOTH', 'HTML', 'STDOUT'],
57 'Set how to output the results received from the API')
58
59gflags.DEFINE_string('credentials_filename', 'events.dat',
60 'File to store credentials in', short_name='cf')
61
62API_FLAGS = {'eventDateMin':None, 'eventDateMax':None, 'advertiserId':None,
63 'publisherId':None, 'orderId':None, 'sku':None,
64 'productCategory':None, 'linkId':None, 'memberId':None,
65 'status':None, 'type':None, 'role':None, 'roleId':None}
66
67gflags.DEFINE_string(
68 'eventDateMin', None,
69 'RFC 3339 formatted min date. Ex: 2005-08-09-T10:57:00-08:00')
70
71gflags.DEFINE_string(
72 'eventDateMax', None,
73 'RFC 3339 formatted max date. Ex: 2005-08-09-T10:57:00-08:00')
74
75gflags.DEFINE_string('advertiserId', None,
76 'caret delimited advertiser IDs')
77
78gflags.DEFINE_string('publisherId', None,
79 'caret delimited publisher IDs')
80
81gflags.DEFINE_string('orderId', None,
82 'caret delimited order IDs')
83
84gflags.DEFINE_string('sku', None,
85 'caret delimited SKUs')
86
87gflags.DEFINE_string('productCategory', None,
88 'caret delimited product categories')
89
90gflags.DEFINE_string('linkId', None,
91 'caret delimited link IDs')
92
93gflags.DEFINE_string('memberId', None,
94 'caret delimited member IDs')
95
96gflags.DEFINE_string('status', None,
97 'status of events - valid values "active" or "cancelled"')
98
99gflags.DEFINE_string('type', None,
100 'type of events - valid values "action" or "transaction"')
101
102
103def usage(argv):
104 print 'Usage: %s <role> <role-id>\n%s' % (argv[0], FLAGS)
105 sys.exit(1)
106
107
108def main(argv):
109 # Let the gflags module process the command-line arguments
110 try:
111 argv = FLAGS(argv)
112 except gflags.FlagsError, e:
113 print e
114 usage(argv)
115
116 if len(argv) != 3:
117 usage(argv)
118 params = {
119 'role': argv[1],
120 'roleId': argv[2]
121 }
122
123 # Set the logging according to the command-line flag
124 logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
125
126 # If the Credentials don't exist or are invalid run through the native client
127 # flow. The Storage object will ensure that if successful the good
128 # Credentials will get written back to a file.
129 storage = Storage(FLAGS.credentials_filename)
130 credentials = storage.get()
131 if credentials is None or credentials.invalid:
132 credentials = run(FLOW, storage)
133
134 # Create an httplib2.Http object to handle our HTTP requests and authorize it
135 # with our good Credentials.
136 http = httplib2.Http()
137 http = credentials.authorize(http)
138
139 service = build('gan', 'v1beta1', http=http)
140
141 events = service.events()
142
143 # Filter out all params that aren't set.
144 for key in FLAGS:
145 if key in API_FLAGS and FLAGS[key].value != None:
146 params[key] = FLAGS[key].value
147
148 # Retrieve the relevant events.
149 try:
150 list_call = events.list(**params)
151 list = list_call.execute()
152 except apiclient.errors.HttpError, e:
153 print json.dumps(e.__dict__, sort_keys=True, indent=4)
154
155 if FLAGS.output_type in ["BOTH", "HTML"]:
156 template = get_template('events_template.html')
157 context = Context(list)
158
159 out = open("output.html", 'w')
160 out.write(template.render(context).encode('UTF-8'))
161 os.fchmod(out.fileno(), stat.S_IROTH|stat.S_IRGRP|stat.S_IRUSR|stat.S_IWUSR)
162 out.close()
163
164 print 'Wrote output.html'
165
166 if FLAGS.output_type in ["BOTH", "STDOUT"]:
167 print json.dumps(list, sort_keys=True, indent=4)
168
169if __name__ == '__main__':
170 main(sys.argv)