PageRenderTime 43ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/gdata/base/service.py

https://github.com/gperciva/git-cl
Python | 256 lines | 171 code | 13 blank | 72 comment | 0 complexity | 252edb3d79a1a01ed2a9cdd20c893883 MD5 | raw file
  1. #!/usr/bin/env python
  2. #
  3. # Copyright (C) 2006 Google Inc.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """GBaseService extends the GDataService to streamline Google Base operations.
  17. GBaseService: Provides methods to query feeds and manipulate items. Extends
  18. GDataService.
  19. DictionaryToParamList: Function which converts a dictionary into a list of
  20. URL arguments (represented as strings). This is a
  21. utility function used in CRUD operations.
  22. """
  23. __author__ = 'api.jscudder (Jeffrey Scudder)'
  24. import urllib
  25. import gdata
  26. import atom.service
  27. import gdata.service
  28. import gdata.base
  29. import atom
  30. # URL to which all batch requests are sent.
  31. BASE_BATCH_URL = 'http://www.google.com/base/feeds/items/batch'
  32. class Error(Exception):
  33. pass
  34. class RequestError(Error):
  35. pass
  36. class GBaseService(gdata.service.GDataService):
  37. """Client for the Google Base service."""
  38. def __init__(self, email=None, password=None, source=None,
  39. server='base.google.com', api_key=None, additional_headers=None,
  40. handler=None, **kwargs):
  41. """Creates a client for the Google Base service.
  42. Args:
  43. email: string (optional) The user's email address, used for
  44. authentication.
  45. password: string (optional) The user's password.
  46. source: string (optional) The name of the user's application.
  47. server: string (optional) The name of the server to which a connection
  48. will be opened. Default value: 'base.google.com'.
  49. api_key: string (optional) The Google Base API key to use.
  50. **kwargs: The other parameters to pass to gdata.service.GDataService
  51. constructor.
  52. """
  53. gdata.service.GDataService.__init__(
  54. self, email=email, password=password, service='gbase', source=source,
  55. server=server, additional_headers=additional_headers, handler=handler,
  56. **kwargs)
  57. self.api_key = api_key
  58. def _SetAPIKey(self, api_key):
  59. if not isinstance(self.additional_headers, dict):
  60. self.additional_headers = {}
  61. self.additional_headers['X-Google-Key'] = api_key
  62. def __SetAPIKey(self, api_key):
  63. self._SetAPIKey(api_key)
  64. def _GetAPIKey(self):
  65. if 'X-Google-Key' not in self.additional_headers:
  66. return None
  67. else:
  68. return self.additional_headers['X-Google-Key']
  69. def __GetAPIKey(self):
  70. return self._GetAPIKey()
  71. api_key = property(__GetAPIKey, __SetAPIKey,
  72. doc="""Get or set the API key to be included in all requests.""")
  73. def Query(self, uri, converter=None):
  74. """Performs a style query and returns a resulting feed or entry.
  75. Args:
  76. uri: string The full URI which be queried. Examples include
  77. '/base/feeds/snippets?bq=digital+camera',
  78. 'http://www.google.com/base/feeds/snippets?bq=digital+camera'
  79. '/base/feeds/items'
  80. I recommend creating a URI using a query class.
  81. converter: func (optional) A function which will be executed on the
  82. server's response. Examples include GBaseItemFromString, etc.
  83. Returns:
  84. If converter was specified, returns the results of calling converter on
  85. the server's response. If converter was not specified, and the result
  86. was an Atom Entry, returns a GBaseItem, by default, the method returns
  87. the result of calling gdata.service's Get method.
  88. """
  89. result = self.Get(uri, converter=converter)
  90. if converter:
  91. return result
  92. elif isinstance(result, atom.Entry):
  93. return gdata.base.GBaseItemFromString(result.ToString())
  94. return result
  95. def QuerySnippetsFeed(self, uri):
  96. return self.Get(uri, converter=gdata.base.GBaseSnippetFeedFromString)
  97. def QueryItemsFeed(self, uri):
  98. return self.Get(uri, converter=gdata.base.GBaseItemFeedFromString)
  99. def QueryAttributesFeed(self, uri):
  100. return self.Get(uri, converter=gdata.base.GBaseAttributesFeedFromString)
  101. def QueryItemTypesFeed(self, uri):
  102. return self.Get(uri, converter=gdata.base.GBaseItemTypesFeedFromString)
  103. def QueryLocalesFeed(self, uri):
  104. return self.Get(uri, converter=gdata.base.GBaseLocalesFeedFromString)
  105. def GetItem(self, uri):
  106. return self.Get(uri, converter=gdata.base.GBaseItemFromString)
  107. def GetSnippet(self, uri):
  108. return self.Get(uri, converter=gdata.base.GBaseSnippetFromString)
  109. def GetAttribute(self, uri):
  110. return self.Get(uri, converter=gdata.base.GBaseAttributeEntryFromString)
  111. def GetItemType(self, uri):
  112. return self.Get(uri, converter=gdata.base.GBaseItemTypeEntryFromString)
  113. def GetLocale(self, uri):
  114. return self.Get(uri, converter=gdata.base.GDataEntryFromString)
  115. def InsertItem(self, new_item, url_params=None, escape_params=True,
  116. converter=None):
  117. """Adds an item to Google Base.
  118. Args:
  119. new_item: atom.Entry or subclass A new item which is to be added to
  120. Google Base.
  121. url_params: dict (optional) Additional URL parameters to be included
  122. in the insertion request.
  123. escape_params: boolean (optional) If true, the url_parameters will be
  124. escaped before they are included in the request.
  125. converter: func (optional) Function which is executed on the server's
  126. response before it is returned. Usually this is a function like
  127. GBaseItemFromString which will parse the response and turn it into
  128. an object.
  129. Returns:
  130. If converter is defined, the results of running converter on the server's
  131. response. Otherwise, it will be a GBaseItem.
  132. """
  133. response = self.Post(new_item, '/base/feeds/items', url_params=url_params,
  134. escape_params=escape_params, converter=converter)
  135. if not converter and isinstance(response, atom.Entry):
  136. return gdata.base.GBaseItemFromString(response.ToString())
  137. return response
  138. def DeleteItem(self, item_id, url_params=None, escape_params=True):
  139. """Removes an item with the specified ID from Google Base.
  140. Args:
  141. item_id: string The ID of the item to be deleted. Example:
  142. 'http://www.google.com/base/feeds/items/13185446517496042648'
  143. url_params: dict (optional) Additional URL parameters to be included
  144. in the deletion request.
  145. escape_params: boolean (optional) If true, the url_parameters will be
  146. escaped before they are included in the request.
  147. Returns:
  148. True if the delete succeeded.
  149. """
  150. return self.Delete('%s' % (item_id[len('http://www.google.com'):],),
  151. url_params=url_params, escape_params=escape_params)
  152. def UpdateItem(self, item_id, updated_item, url_params=None,
  153. escape_params=True,
  154. converter=gdata.base.GBaseItemFromString):
  155. """Updates an existing item.
  156. Args:
  157. item_id: string The ID of the item to be updated. Example:
  158. 'http://www.google.com/base/feeds/items/13185446517496042648'
  159. updated_item: atom.Entry, subclass, or string, containing
  160. the Atom Entry which will replace the base item which is
  161. stored at the item_id.
  162. url_params: dict (optional) Additional URL parameters to be included
  163. in the update request.
  164. escape_params: boolean (optional) If true, the url_parameters will be
  165. escaped before they are included in the request.
  166. converter: func (optional) Function which is executed on the server's
  167. response before it is returned. Usually this is a function like
  168. GBaseItemFromString which will parse the response and turn it into
  169. an object.
  170. Returns:
  171. If converter is defined, the results of running converter on the server's
  172. response. Otherwise, it will be a GBaseItem.
  173. """
  174. response = self.Put(updated_item,
  175. item_id, url_params=url_params, escape_params=escape_params,
  176. converter=converter)
  177. if not converter and isinstance(response, atom.Entry):
  178. return gdata.base.GBaseItemFromString(response.ToString())
  179. return response
  180. def ExecuteBatch(self, batch_feed,
  181. converter=gdata.base.GBaseItemFeedFromString):
  182. """Sends a batch request feed to the server.
  183. Args:
  184. batch_feed: gdata.BatchFeed A feed containing BatchEntry elements which
  185. contain the desired CRUD operation and any necessary entry data.
  186. converter: Function (optional) Function to be executed on the server's
  187. response. This function should take one string as a parameter. The
  188. default value is GBaseItemFeedFromString which will turn the result
  189. into a gdata.base.GBaseItem object.
  190. Returns:
  191. A gdata.BatchFeed containing the results.
  192. """
  193. return self.Post(batch_feed, BASE_BATCH_URL, converter=converter)
  194. class BaseQuery(gdata.service.Query):
  195. def _GetBaseQuery(self):
  196. return self['bq']
  197. def _SetBaseQuery(self, base_query):
  198. self['bq'] = base_query
  199. bq = property(_GetBaseQuery, _SetBaseQuery,
  200. doc="""The bq query parameter""")