PageRenderTime 54ms CodeModel.GetById 38ms app.highlight 12ms RepoModel.GetById 1ms app.codeStats 1ms

/gdata/base/service.py

http://radioappz.googlecode.com/
Python | 256 lines | 171 code | 13 blank | 72 comment | 0 complexity | 49d05d4484942cbf7d09378e4e75bac2 MD5 | raw file
  1#!/usr/bin/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
 17"""GBaseService extends the GDataService to streamline Google Base operations.
 18
 19  GBaseService: Provides methods to query feeds and manipulate items. Extends 
 20                GDataService.
 21
 22  DictionaryToParamList: Function which converts a dictionary into a list of 
 23                         URL arguments (represented as strings). This is a 
 24                         utility function used in CRUD operations.
 25"""
 26
 27__author__ = 'api.jscudder (Jeffrey Scudder)'
 28
 29import urllib
 30import gdata
 31import atom.service
 32import gdata.service
 33import gdata.base
 34import atom
 35
 36
 37# URL to which all batch requests are sent.
 38BASE_BATCH_URL = 'http://www.google.com/base/feeds/items/batch'
 39
 40
 41class Error(Exception):
 42  pass
 43
 44
 45class RequestError(Error):
 46  pass
 47
 48
 49class GBaseService(gdata.service.GDataService):
 50  """Client for the Google Base service."""
 51
 52  def __init__(self, email=None, password=None, source=None,
 53               server='base.google.com', api_key=None, additional_headers=None,
 54               handler=None, **kwargs):
 55    """Creates a client for the Google Base service.
 56
 57    Args:
 58      email: string (optional) The user's email address, used for
 59          authentication.
 60      password: string (optional) The user's password.
 61      source: string (optional) The name of the user's application.
 62      server: string (optional) The name of the server to which a connection
 63          will be opened. Default value: 'base.google.com'.
 64      api_key: string (optional) The Google Base API key to use.
 65      **kwargs: The other parameters to pass to gdata.service.GDataService
 66          constructor.
 67    """
 68    gdata.service.GDataService.__init__(
 69        self, email=email, password=password, service='gbase', source=source,
 70        server=server, additional_headers=additional_headers, handler=handler,
 71        **kwargs)
 72    self.api_key = api_key
 73
 74  def _SetAPIKey(self, api_key):
 75    if not isinstance(self.additional_headers, dict):
 76      self.additional_headers = {}
 77    self.additional_headers['X-Google-Key'] = api_key
 78
 79  def __SetAPIKey(self, api_key):
 80    self._SetAPIKey(api_key)
 81
 82  def _GetAPIKey(self):
 83    if 'X-Google-Key' not in self.additional_headers:
 84      return None
 85    else:
 86      return self.additional_headers['X-Google-Key']
 87
 88  def __GetAPIKey(self):
 89    return self._GetAPIKey()
 90
 91  api_key = property(__GetAPIKey, __SetAPIKey,
 92      doc="""Get or set the API key to be included in all requests.""")
 93    
 94  def Query(self, uri, converter=None):
 95    """Performs a style query and returns a resulting feed or entry.
 96
 97    Args:
 98      uri: string The full URI which be queried. Examples include
 99          '/base/feeds/snippets?bq=digital+camera', 
100          'http://www.google.com/base/feeds/snippets?bq=digital+camera'
101          '/base/feeds/items'
102          I recommend creating a URI using a query class.
103      converter: func (optional) A function which will be executed on the
104          server's response. Examples include GBaseItemFromString, etc. 
105
106    Returns:
107      If converter was specified, returns the results of calling converter on
108      the server's response. If converter was not specified, and the result
109      was an Atom Entry, returns a GBaseItem, by default, the method returns
110      the result of calling gdata.service's Get method.
111    """
112 
113    result = self.Get(uri, converter=converter)
114    if converter:
115      return result
116    elif isinstance(result, atom.Entry):
117      return gdata.base.GBaseItemFromString(result.ToString())
118    return result
119
120  def QuerySnippetsFeed(self, uri):
121    return self.Get(uri, converter=gdata.base.GBaseSnippetFeedFromString)
122
123  def QueryItemsFeed(self, uri):
124    return self.Get(uri, converter=gdata.base.GBaseItemFeedFromString)
125
126  def QueryAttributesFeed(self, uri):
127    return self.Get(uri, converter=gdata.base.GBaseAttributesFeedFromString)
128
129  def QueryItemTypesFeed(self, uri):
130    return self.Get(uri, converter=gdata.base.GBaseItemTypesFeedFromString)
131
132  def QueryLocalesFeed(self, uri):
133    return self.Get(uri, converter=gdata.base.GBaseLocalesFeedFromString)
134
135  def GetItem(self, uri):
136    return self.Get(uri, converter=gdata.base.GBaseItemFromString)
137
138  def GetSnippet(self, uri):
139    return self.Get(uri, converter=gdata.base.GBaseSnippetFromString)
140
141  def GetAttribute(self, uri):
142    return self.Get(uri, converter=gdata.base.GBaseAttributeEntryFromString)
143
144  def GetItemType(self, uri):
145    return self.Get(uri, converter=gdata.base.GBaseItemTypeEntryFromString)
146
147  def GetLocale(self, uri):
148    return self.Get(uri, converter=gdata.base.GDataEntryFromString)
149
150  def InsertItem(self, new_item, url_params=None, escape_params=True, 
151      converter=None):
152    """Adds an item to Google Base.
153
154    Args: 
155      new_item: atom.Entry or subclass A new item which is to be added to 
156                Google Base.
157      url_params: dict (optional) Additional URL parameters to be included
158                  in the insertion request. 
159      escape_params: boolean (optional) If true, the url_parameters will be
160                     escaped before they are included in the request.
161      converter: func (optional) Function which is executed on the server's
162          response before it is returned. Usually this is a function like
163          GBaseItemFromString which will parse the response and turn it into
164          an object.
165
166    Returns:
167      If converter is defined, the results of running converter on the server's
168      response. Otherwise, it will be a GBaseItem.
169    """
170
171    response = self.Post(new_item, '/base/feeds/items', url_params=url_params,
172                         escape_params=escape_params, converter=converter)
173
174    if not converter and isinstance(response, atom.Entry):
175      return gdata.base.GBaseItemFromString(response.ToString())
176    return response
177
178  def DeleteItem(self, item_id, url_params=None, escape_params=True):
179    """Removes an item with the specified ID from Google Base.
180
181    Args:
182      item_id: string The ID of the item to be deleted. Example:
183               'http://www.google.com/base/feeds/items/13185446517496042648'
184      url_params: dict (optional) Additional URL parameters to be included
185                  in the deletion request.
186      escape_params: boolean (optional) If true, the url_parameters will be
187                     escaped before they are included in the request.
188
189    Returns:
190      True if the delete succeeded.
191    """
192    
193    return self.Delete('%s' % (item_id[len('http://www.google.com'):],),
194                       url_params=url_params, escape_params=escape_params)
195                           
196  def UpdateItem(self, item_id, updated_item, url_params=None, 
197                 escape_params=True, 
198                 converter=gdata.base.GBaseItemFromString):
199    """Updates an existing item.
200
201    Args:
202      item_id: string The ID of the item to be updated.  Example:
203               'http://www.google.com/base/feeds/items/13185446517496042648'
204      updated_item: atom.Entry, subclass, or string, containing
205                    the Atom Entry which will replace the base item which is 
206                    stored at the item_id.
207      url_params: dict (optional) Additional URL parameters to be included
208                  in the update request.
209      escape_params: boolean (optional) If true, the url_parameters will be
210                     escaped before they are included in the request.
211      converter: func (optional) Function which is executed on the server's
212          response before it is returned. Usually this is a function like
213          GBaseItemFromString which will parse the response and turn it into
214          an object.
215
216    Returns:
217      If converter is defined, the results of running converter on the server's
218      response. Otherwise, it will be a GBaseItem.
219    """
220    
221    response = self.Put(updated_item, 
222        item_id, url_params=url_params, escape_params=escape_params, 
223        converter=converter)
224    if not converter and isinstance(response, atom.Entry):
225      return gdata.base.GBaseItemFromString(response.ToString())
226    return response
227
228  def ExecuteBatch(self, batch_feed, 
229                   converter=gdata.base.GBaseItemFeedFromString):
230    """Sends a batch request feed to the server.
231    
232    Args: 
233      batch_feed: gdata.BatchFeed A feed containing BatchEntry elements which
234          contain the desired CRUD operation and any necessary entry data.
235      converter: Function (optional) Function to be executed on the server's
236          response. This function should take one string as a parameter. The
237          default value is GBaseItemFeedFromString which will turn the result 
238          into a gdata.base.GBaseItem object.
239
240    Returns:
241      A gdata.BatchFeed containing the results.
242    """
243    
244    return self.Post(batch_feed, BASE_BATCH_URL, converter=converter) 
245
246
247class BaseQuery(gdata.service.Query):
248
249  def _GetBaseQuery(self):
250    return self['bq']
251
252  def _SetBaseQuery(self, base_query):
253    self['bq'] = base_query
254
255  bq = property(_GetBaseQuery, _SetBaseQuery, 
256      doc="""The bq query parameter""")