PageRenderTime 58ms CodeModel.GetById 13ms app.highlight 39ms RepoModel.GetById 1ms app.codeStats 0ms

/gdata/analytics/service.py

http://radioappz.googlecode.com/
Python | 331 lines | 294 code | 9 blank | 28 comment | 0 complexity | 3374534e1d7be06867a046f3af51d0c0 MD5 | raw file
  1#!/usr/bin/python
  2#
  3# Copyright (C) 2006 Google Inc.
  4# Refactored in 2009 to work for Google Analytics by Sal Uryasev at Juice Inc.
  5#
  6# Licensed under the Apache License, Version 2.0 (the "License");
  7# you may not use this file except in compliance with the License.
  8# You may obtain a copy of the License at
  9#
 10#      http://www.apache.org/licenses/LICENSE-2.0
 11#
 12# Unless required by applicable law or agreed to in writing, software
 13# distributed under the License is distributed on an "AS IS" BASIS,
 14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 15# See the License for the specific language governing permissions and
 16# limitations under the License.
 17
 18"""
 19  AccountsService extends the GDataService to streamline Google Analytics
 20            account information operations.
 21
 22  AnalyticsDataService: Provides methods to query google analytics data feeds.
 23                    Extends GDataService.
 24
 25  DataQuery: Queries a Google Analytics Data list feed.
 26  
 27  AccountQuery: Queries a Google Analytics Account list feed.
 28"""
 29
 30
 31__author__ = 'api.suryasev (Sal Uryasev)'
 32
 33
 34import urllib
 35import atom
 36import gdata.service
 37import gdata.analytics
 38
 39
 40class AccountsService(gdata.service.GDataService):
 41
 42  """Client extension for the Google Analytics Account List feed."""
 43
 44  def __init__(self, email="", password=None, source=None,
 45               server='www.google.com/analytics', additional_headers=None, 
 46               **kwargs):
 47    """Creates a client for the Google Analytics service.
 48
 49    Args:
 50      email: string (optional) The user's email address, used for
 51          authentication.
 52      password: string (optional) The user's password.
 53      source: string (optional) The name of the user's application.
 54      server: string (optional) The name of the server to which a connection
 55          will be opened.
 56      **kwargs: The other parameters to pass to gdata.service.GDataService
 57          constructor.
 58    """
 59    
 60    gdata.service.GDataService.__init__(
 61        self, email=email, password=password, service='analytics', 
 62        source=source, server=server, additional_headers=additional_headers,
 63        **kwargs)
 64
 65  def QueryAccountListFeed(self, uri):
 66    """Retrieves an AccountListFeed by retrieving a URI based off the Document
 67       List feed, including any query parameters. An AccountListFeed object 
 68       can be used to construct these parameters.
 69
 70    Args:
 71      uri: string The URI of the feed being retrieved possibly with query
 72           parameters.
 73
 74    Returns:
 75      An AccountListFeed object representing the feed returned by the server.
 76    """
 77    return self.Get(uri, converter=gdata.analytics.AccountListFeedFromString)
 78
 79  def GetAccountListEntry(self, uri):
 80    """Retrieves a particular AccountListEntry by its unique URI.
 81
 82    Args:
 83      uri: string The unique URI of an entry in an Account List feed.
 84
 85    Returns:
 86      An AccountLisFeed object representing the retrieved entry.
 87      """
 88    return self.Get(uri, converter=gdata.analytics.AccountListEntryFromString)
 89
 90  def GetAccountList(self, max_results=1000, text_query=None,
 91                     params=None, categories=None):
 92    """Retrieves a feed containing all of a user's accounts and profiles."""
 93    q = gdata.analytics.service.AccountQuery(max_results=max_results,
 94                                             text_query=text_query, 
 95                                             params=params,
 96                                             categories=categories);
 97    return self.QueryAccountListFeed(q.ToUri())
 98
 99
100
101
102class AnalyticsDataService(gdata.service.GDataService):
103
104  """Client extension for the Google Analytics service Data List feed."""
105
106  def __init__(self, email=None, password=None, source=None,
107               server='www.google.com/analytics', additional_headers=None, 
108               **kwargs):
109    """Creates a client for the Google Analytics service.
110
111    Args:
112      email: string (optional) The user's email address, used for
113          authentication.
114      password: string (optional) The user's password.
115      source: string (optional) The name of the user's application.
116      server: string (optional) The name of the server to which a connection
117          will be opened. Default value: 'docs.google.com'.
118      **kwargs: The other parameters to pass to gdata.service.GDataService
119          constructor.
120    """
121    
122    gdata.service.GDataService.__init__(self, 
123        email=email, password=password, service='analytics', source=source,
124        server=server, additional_headers=additional_headers, **kwargs)
125    
126  def GetData(self, ids='', dimensions='', metrics='',
127              sort='', filters='', start_date='',
128              end_date='', start_index='',
129              max_results=''):
130    """Retrieves a feed containing a user's data
131    
132      ids: comma-separated string of analytics accounts.
133      dimensions: comma-separated string of dimensions.
134      metrics: comma-separated string of metrics.
135      sort: comma-separated string of dimensions and metrics for sorting.
136            This may be previxed with a minus to sort in reverse order. 
137                (e.g. '-ga:keyword')
138            If ommited, the first dimension passed in will be used.
139      filters: comma-separated string of filter parameters.
140            (e.g. 'ga:keyword==google')
141      start_date: start date for data pull.
142      end_date: end date for data pull.
143      start_index: used in combination with max_results to pull more than 1000 
144            entries. This defaults to 1.
145      max_results: maximum results that the pull will return.  This defaults
146            to, and maxes out at 1000.
147    """
148    q = gdata.analytics.service.DataQuery(ids=ids, 
149                                          dimensions=dimensions,
150                                          metrics=metrics,
151                                          filters=filters,
152                                          sort=sort,
153                                          start_date=start_date,
154                                          end_date=end_date,
155                                          start_index=start_index,
156                                          max_results=max_results);
157    return self.AnalyticsDataFeed(q.ToUri())
158    
159  def AnalyticsDataFeed(self, uri):
160    """Retrieves an AnalyticsListFeed by retrieving a URI based off the 
161       Document List feed, including any query parameters. An 
162       AnalyticsListFeed object can be used to construct these parameters.
163
164    Args:
165      uri: string The URI of the feed being retrieved possibly with query
166           parameters.
167
168    Returns:
169      An AnalyticsListFeed object representing the feed returned by the 
170      server.
171    """
172    return self.Get(uri,
173                    converter=gdata.analytics.AnalyticsDataFeedFromString)
174    
175  """
176  Account Fetching
177  """    
178    
179  def QueryAccountListFeed(self, uri):
180    """Retrieves an Account ListFeed by retrieving a URI based off the Account
181       List feed, including any query parameters. A AccountQuery object can
182       be used to construct these parameters.
183
184    Args:
185      uri: string The URI of the feed being retrieved possibly with query
186           parameters.
187
188    Returns:
189      An AccountListFeed object representing the feed returned by the server.
190    """
191    return self.Get(uri, converter=gdata.analytics.AccountListFeedFromString)
192
193  def GetAccountListEntry(self, uri):
194    """Retrieves a particular AccountListEntry by its unique URI.
195
196    Args:
197      uri: string The unique URI of an entry in an Account List feed.
198
199    Returns:
200      An AccountListEntry object representing the retrieved entry.
201      """
202    return self.Get(uri, converter=gdata.analytics.AccountListEntryFromString)
203
204  def GetAccountList(self, username="default", max_results=1000, 
205                     start_index=1):
206    """Retrieves a feed containing all of a user's accounts and profiles.
207       The username parameter is soon to be deprecated, with 'default' 
208       becoming the only allowed parameter.
209    """
210    if not username:
211      raise Exception("username is a required parameter")
212    q = gdata.analytics.service.AccountQuery(username=username, 
213                                             max_results=max_results,
214                                             start_index=start_index);
215    return self.QueryAccountListFeed(q.ToUri())
216
217class DataQuery(gdata.service.Query):
218  """Object used to construct a URI to a data feed"""
219  def __init__(self, feed='/feeds/data', text_query=None, 
220               params=None, categories=None, ids="",
221               dimensions="", metrics="", sort="", filters="",
222               start_date="", end_date="", start_index="",
223               max_results=""):
224    """Constructor for Analytics List Query
225
226    Args:
227      feed: string (optional) The path for the feed. (e.g. '/feeds/data')
228
229      text_query: string (optional) The contents of the q query parameter. 
230            This string is URL escaped upon conversion to a URI.
231      params: dict (optional) Parameter value string pairs which become URL
232            params when translated to a URI. These parameters are added to
233              the query's items.
234      categories: list (optional) List of category strings which should be
235            included as query categories. See gdata.service.Query for
236            additional documentation.
237      ids: comma-separated string of analytics accounts.
238      dimensions: comma-separated string of dimensions.
239      metrics: comma-separated string of metrics.
240      sort: comma-separated string of dimensions and metrics.
241            This may be previxed with a minus to sort in reverse order 
242            (e.g. '-ga:keyword').
243            If ommited, the first dimension passed in will be used.
244      filters: comma-separated string of filter parameters 
245            (e.g. 'ga:keyword==google').
246      start_date: start date for data pull.
247      end_date: end date for data pull.
248      start_index: used in combination with max_results to pull more than 1000 
249            entries. This defaults to 1.
250      max_results: maximum results that the pull will return.  This defaults 
251            to, and maxes out at 1000.
252
253    Yields:
254      A DocumentQuery object used to construct a URI based on the Document
255      List feed.
256    """
257    self.elements = {'ids': ids,
258                     'dimensions': dimensions,
259                     'metrics': metrics,
260                     'sort': sort,
261                     'filters': filters,
262                     'start-date': start_date,
263                     'end-date': end_date,
264                     'start-index': start_index,
265                     'max-results': max_results}
266    
267    gdata.service.Query.__init__(self, feed, text_query, params, categories)
268  
269  def ToUri(self):
270    """Generates a URI from the query parameters set in the object.
271
272    Returns:
273      A string containing the URI used to retrieve entries from the Analytics
274      List feed.
275    """
276    old_feed = self.feed
277    self.feed = '/'.join([old_feed]) + '?' + \
278                urllib.urlencode(dict([(key, value) for key, value in \
279                self.elements.iteritems() if value]))
280    new_feed = gdata.service.Query.ToUri(self)
281    self.feed = old_feed
282    return new_feed
283
284
285class AccountQuery(gdata.service.Query):
286  """Object used to construct a URI to query the Google Account List feed"""
287  def __init__(self, feed='/feeds/accounts', start_index=1,
288               max_results=1000, username='default', text_query=None,
289               params=None, categories=None):
290    """Constructor for Account List Query
291
292    Args:
293      feed: string (optional) The path for the feed. (e.g. '/feeds/documents')
294      visibility: string (optional) The visibility chosen for the current 
295            feed.
296      projection: string (optional) The projection chosen for the current 
297            feed.
298      text_query: string (optional) The contents of the q query parameter. 
299            This string is URL escaped upon conversion to a URI.
300      params: dict (optional) Parameter value string pairs which become URL
301              params when translated to a URI. These parameters are added to
302              the query's items.
303      categories: list (optional) List of category strings which should be
304              included as query categories. See gdata.service.Query for
305              additional documentation.
306      username: string (deprecated) This value should now always be passed as 
307              'default'.
308
309    Yields:
310      A DocumentQuery object used to construct a URI based on the Document
311      List feed.
312    """
313    self.max_results = max_results
314    self.start_index = start_index
315    self.username = username
316    gdata.service.Query.__init__(self, feed, text_query, params, categories)
317  
318  def ToUri(self):
319    """Generates a URI from the query parameters set in the object.
320
321    Returns:
322      A string containing the URI used to retrieve entries from the Account
323      List feed.
324    """
325    old_feed = self.feed
326    self.feed = '/'.join([old_feed, self.username]) + '?' + \
327                '&'.join(['max-results=' + str(self.max_results), 
328                          'start-index=' + str(self.start_index)])
329    new_feed = self.feed
330    self.feed = old_feed
331    return new_feed