/gdata/analytics/service.py

http://radioappz.googlecode.com/ · Python · 331 lines · 239 code · 20 blank · 72 comment · 18 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. AccountsService extends the GDataService to streamline Google Analytics
  19. account information operations.
  20. AnalyticsDataService: Provides methods to query google analytics data feeds.
  21. Extends GDataService.
  22. DataQuery: Queries a Google Analytics Data list feed.
  23. AccountQuery: Queries a Google Analytics Account list feed.
  24. """
  25. __author__ = 'api.suryasev (Sal Uryasev)'
  26. import urllib
  27. import atom
  28. import gdata.service
  29. import gdata.analytics
  30. class AccountsService(gdata.service.GDataService):
  31. """Client extension for the Google Analytics Account List feed."""
  32. def __init__(self, email="", password=None, source=None,
  33. server='www.google.com/analytics', additional_headers=None,
  34. **kwargs):
  35. """Creates a client for the Google Analytics service.
  36. Args:
  37. email: string (optional) The user's email address, used for
  38. authentication.
  39. password: string (optional) The user's password.
  40. source: string (optional) The name of the user's application.
  41. server: string (optional) The name of the server to which a connection
  42. will be opened.
  43. **kwargs: The other parameters to pass to gdata.service.GDataService
  44. constructor.
  45. """
  46. gdata.service.GDataService.__init__(
  47. self, email=email, password=password, service='analytics',
  48. source=source, server=server, additional_headers=additional_headers,
  49. **kwargs)
  50. def QueryAccountListFeed(self, uri):
  51. """Retrieves an AccountListFeed by retrieving a URI based off the Document
  52. List feed, including any query parameters. An AccountListFeed object
  53. can be used to construct these parameters.
  54. Args:
  55. uri: string The URI of the feed being retrieved possibly with query
  56. parameters.
  57. Returns:
  58. An AccountListFeed object representing the feed returned by the server.
  59. """
  60. return self.Get(uri, converter=gdata.analytics.AccountListFeedFromString)
  61. def GetAccountListEntry(self, uri):
  62. """Retrieves a particular AccountListEntry by its unique URI.
  63. Args:
  64. uri: string The unique URI of an entry in an Account List feed.
  65. Returns:
  66. An AccountLisFeed object representing the retrieved entry.
  67. """
  68. return self.Get(uri, converter=gdata.analytics.AccountListEntryFromString)
  69. def GetAccountList(self, max_results=1000, text_query=None,
  70. params=None, categories=None):
  71. """Retrieves a feed containing all of a user's accounts and profiles."""
  72. q = gdata.analytics.service.AccountQuery(max_results=max_results,
  73. text_query=text_query,
  74. params=params,
  75. categories=categories);
  76. return self.QueryAccountListFeed(q.ToUri())
  77. class AnalyticsDataService(gdata.service.GDataService):
  78. """Client extension for the Google Analytics service Data List feed."""
  79. def __init__(self, email=None, password=None, source=None,
  80. server='www.google.com/analytics', additional_headers=None,
  81. **kwargs):
  82. """Creates a client for the Google Analytics service.
  83. Args:
  84. email: string (optional) The user's email address, used for
  85. authentication.
  86. password: string (optional) The user's password.
  87. source: string (optional) The name of the user's application.
  88. server: string (optional) The name of the server to which a connection
  89. will be opened. Default value: 'docs.google.com'.
  90. **kwargs: The other parameters to pass to gdata.service.GDataService
  91. constructor.
  92. """
  93. gdata.service.GDataService.__init__(self,
  94. email=email, password=password, service='analytics', source=source,
  95. server=server, additional_headers=additional_headers, **kwargs)
  96. def GetData(self, ids='', dimensions='', metrics='',
  97. sort='', filters='', start_date='',
  98. end_date='', start_index='',
  99. max_results=''):
  100. """Retrieves a feed containing a user's data
  101. ids: comma-separated string of analytics accounts.
  102. dimensions: comma-separated string of dimensions.
  103. metrics: comma-separated string of metrics.
  104. sort: comma-separated string of dimensions and metrics for sorting.
  105. This may be previxed with a minus to sort in reverse order.
  106. (e.g. '-ga:keyword')
  107. If ommited, the first dimension passed in will be used.
  108. filters: comma-separated string of filter parameters.
  109. (e.g. 'ga:keyword==google')
  110. start_date: start date for data pull.
  111. end_date: end date for data pull.
  112. start_index: used in combination with max_results to pull more than 1000
  113. entries. This defaults to 1.
  114. max_results: maximum results that the pull will return. This defaults
  115. to, and maxes out at 1000.
  116. """
  117. q = gdata.analytics.service.DataQuery(ids=ids,
  118. dimensions=dimensions,
  119. metrics=metrics,
  120. filters=filters,
  121. sort=sort,
  122. start_date=start_date,
  123. end_date=end_date,
  124. start_index=start_index,
  125. max_results=max_results);
  126. return self.AnalyticsDataFeed(q.ToUri())
  127. def AnalyticsDataFeed(self, uri):
  128. """Retrieves an AnalyticsListFeed by retrieving a URI based off the
  129. Document List feed, including any query parameters. An
  130. AnalyticsListFeed object can be used to construct these parameters.
  131. Args:
  132. uri: string The URI of the feed being retrieved possibly with query
  133. parameters.
  134. Returns:
  135. An AnalyticsListFeed object representing the feed returned by the
  136. server.
  137. """
  138. return self.Get(uri,
  139. converter=gdata.analytics.AnalyticsDataFeedFromString)
  140. """
  141. Account Fetching
  142. """
  143. def QueryAccountListFeed(self, uri):
  144. """Retrieves an Account ListFeed by retrieving a URI based off the Account
  145. List feed, including any query parameters. A AccountQuery object can
  146. be used to construct these parameters.
  147. Args:
  148. uri: string The URI of the feed being retrieved possibly with query
  149. parameters.
  150. Returns:
  151. An AccountListFeed object representing the feed returned by the server.
  152. """
  153. return self.Get(uri, converter=gdata.analytics.AccountListFeedFromString)
  154. def GetAccountListEntry(self, uri):
  155. """Retrieves a particular AccountListEntry by its unique URI.
  156. Args:
  157. uri: string The unique URI of an entry in an Account List feed.
  158. Returns:
  159. An AccountListEntry object representing the retrieved entry.
  160. """
  161. return self.Get(uri, converter=gdata.analytics.AccountListEntryFromString)
  162. def GetAccountList(self, username="default", max_results=1000,
  163. start_index=1):
  164. """Retrieves a feed containing all of a user's accounts and profiles.
  165. The username parameter is soon to be deprecated, with 'default'
  166. becoming the only allowed parameter.
  167. """
  168. if not username:
  169. raise Exception("username is a required parameter")
  170. q = gdata.analytics.service.AccountQuery(username=username,
  171. max_results=max_results,
  172. start_index=start_index);
  173. return self.QueryAccountListFeed(q.ToUri())
  174. class DataQuery(gdata.service.Query):
  175. """Object used to construct a URI to a data feed"""
  176. def __init__(self, feed='/feeds/data', text_query=None,
  177. params=None, categories=None, ids="",
  178. dimensions="", metrics="", sort="", filters="",
  179. start_date="", end_date="", start_index="",
  180. max_results=""):
  181. """Constructor for Analytics List Query
  182. Args:
  183. feed: string (optional) The path for the feed. (e.g. '/feeds/data')
  184. text_query: string (optional) The contents of the q query parameter.
  185. This string is URL escaped upon conversion to a URI.
  186. params: dict (optional) Parameter value string pairs which become URL
  187. params when translated to a URI. These parameters are added to
  188. the query's items.
  189. categories: list (optional) List of category strings which should be
  190. included as query categories. See gdata.service.Query for
  191. additional documentation.
  192. ids: comma-separated string of analytics accounts.
  193. dimensions: comma-separated string of dimensions.
  194. metrics: comma-separated string of metrics.
  195. sort: comma-separated string of dimensions and metrics.
  196. This may be previxed with a minus to sort in reverse order
  197. (e.g. '-ga:keyword').
  198. If ommited, the first dimension passed in will be used.
  199. filters: comma-separated string of filter parameters
  200. (e.g. 'ga:keyword==google').
  201. start_date: start date for data pull.
  202. end_date: end date for data pull.
  203. start_index: used in combination with max_results to pull more than 1000
  204. entries. This defaults to 1.
  205. max_results: maximum results that the pull will return. This defaults
  206. to, and maxes out at 1000.
  207. Yields:
  208. A DocumentQuery object used to construct a URI based on the Document
  209. List feed.
  210. """
  211. self.elements = {'ids': ids,
  212. 'dimensions': dimensions,
  213. 'metrics': metrics,
  214. 'sort': sort,
  215. 'filters': filters,
  216. 'start-date': start_date,
  217. 'end-date': end_date,
  218. 'start-index': start_index,
  219. 'max-results': max_results}
  220. gdata.service.Query.__init__(self, feed, text_query, params, categories)
  221. def ToUri(self):
  222. """Generates a URI from the query parameters set in the object.
  223. Returns:
  224. A string containing the URI used to retrieve entries from the Analytics
  225. List feed.
  226. """
  227. old_feed = self.feed
  228. self.feed = '/'.join([old_feed]) + '?' + \
  229. urllib.urlencode(dict([(key, value) for key, value in \
  230. self.elements.iteritems() if value]))
  231. new_feed = gdata.service.Query.ToUri(self)
  232. self.feed = old_feed
  233. return new_feed
  234. class AccountQuery(gdata.service.Query):
  235. """Object used to construct a URI to query the Google Account List feed"""
  236. def __init__(self, feed='/feeds/accounts', start_index=1,
  237. max_results=1000, username='default', text_query=None,
  238. params=None, categories=None):
  239. """Constructor for Account List Query
  240. Args:
  241. feed: string (optional) The path for the feed. (e.g. '/feeds/documents')
  242. visibility: string (optional) The visibility chosen for the current
  243. feed.
  244. projection: string (optional) The projection chosen for the current
  245. feed.
  246. text_query: string (optional) The contents of the q query parameter.
  247. This string is URL escaped upon conversion to a URI.
  248. params: dict (optional) Parameter value string pairs which become URL
  249. params when translated to a URI. These parameters are added to
  250. the query's items.
  251. categories: list (optional) List of category strings which should be
  252. included as query categories. See gdata.service.Query for
  253. additional documentation.
  254. username: string (deprecated) This value should now always be passed as
  255. 'default'.
  256. Yields:
  257. A DocumentQuery object used to construct a URI based on the Document
  258. List feed.
  259. """
  260. self.max_results = max_results
  261. self.start_index = start_index
  262. self.username = username
  263. gdata.service.Query.__init__(self, feed, text_query, params, categories)
  264. def ToUri(self):
  265. """Generates a URI from the query parameters set in the object.
  266. Returns:
  267. A string containing the URI used to retrieve entries from the Account
  268. List feed.
  269. """
  270. old_feed = self.feed
  271. self.feed = '/'.join([old_feed, self.username]) + '?' + \
  272. '&'.join(['max-results=' + str(self.max_results),
  273. 'start-index=' + str(self.start_index)])
  274. new_feed = self.feed
  275. self.feed = old_feed
  276. return new_feed