blob: b307a53a79a7bd99c4f6ac60d6f383a6cc5ecac8 [file] [log] [blame]
Joe Gregorio48d361f2010-08-18 13:19:21 -04001# Copyright (C) 2010 Google Inc.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""Client for discovery based APIs
16
Joe Gregorio7c22ab22011-02-16 15:32:39 -050017A client library for Google's discovery based APIs.
Joe Gregorio48d361f2010-08-18 13:19:21 -040018"""
19
20__author__ = 'jcgregorio@google.com (Joe Gregorio)'
Joe Gregorioabda96f2011-02-11 20:19:33 -050021__all__ = [
22 'build', 'build_from_document'
23 ]
Joe Gregorio48d361f2010-08-18 13:19:21 -040024
25import httplib2
ade@google.com850cf552010-08-20 23:24:56 +010026import logging
Joe Gregorio6d5e94f2010-08-25 23:49:30 -040027import os
Joe Gregorio48d361f2010-08-18 13:19:21 -040028import re
Joe Gregorio48d361f2010-08-18 13:19:21 -040029import uritemplate
Joe Gregoriofe695fb2010-08-30 12:04:04 -040030import urllib
Joe Gregorio6d5e94f2010-08-25 23:49:30 -040031import urlparse
ade@google.comc5eb46f2010-09-27 23:35:39 +010032try:
33 from urlparse import parse_qsl
34except ImportError:
35 from cgi import parse_qsl
Joe Gregorioaf276d22010-12-09 14:26:58 -050036
Joe Gregoriob843fa22010-12-13 16:26:07 -050037from http import HttpRequest
Joe Gregorio034e7002010-12-15 08:45:03 -050038from anyjson import simplejson
Joe Gregoriob843fa22010-12-13 16:26:07 -050039from model import JsonModel
Joe Gregoriob843fa22010-12-13 16:26:07 -050040from errors import UnknownLinkType
Joe Gregorio48d361f2010-08-18 13:19:21 -040041
Joe Gregoriobc2ff9b2010-11-08 09:20:48 -050042URITEMPLATE = re.compile('{[^}]*}')
43VARNAME = re.compile('[a-zA-Z0-9_-]+')
Joe Gregorioc3fae8a2011-02-18 14:19:50 -050044DISCOVERY_URI = ('https://www.googleapis.com/discovery/v0.3/describe/'
Joe Gregorio2379ecc2010-10-26 10:51:28 -040045 '{api}/{apiVersion}')
Joe Gregorioc3fae8a2011-02-18 14:19:50 -050046DEFAULT_METHOD_DOC = 'A description of how to use this function'
Joe Gregorioca876e42011-02-22 19:39:42 -050047
48# Query parameters that work, but don't appear in discovery
Joe Gregorio13217952011-02-22 15:37:38 -050049STACK_QUERY_PARAMETERS = ['trace']
Joe Gregorio48d361f2010-08-18 13:19:21 -040050
51
Joe Gregorio48d361f2010-08-18 13:19:21 -040052def key2param(key):
Joe Gregorio7c22ab22011-02-16 15:32:39 -050053 """Converts key names into parameter names.
54
55 For example, converting "max-results" -> "max_results"
Joe Gregorio48d361f2010-08-18 13:19:21 -040056 """
57 result = []
58 key = list(key)
59 if not key[0].isalpha():
60 result.append('x')
61 for c in key:
62 if c.isalnum():
63 result.append(c)
64 else:
65 result.append('_')
66
67 return ''.join(result)
68
69
Joe Gregorioaf276d22010-12-09 14:26:58 -050070def build(serviceName, version,
Joe Gregorio3fada332011-01-07 17:07:45 -050071 http=None,
72 discoveryServiceUrl=DISCOVERY_URI,
73 developerKey=None,
Joe Gregoriod433b2a2011-02-22 10:51:51 -050074 model=None,
Joe Gregorio3fada332011-01-07 17:07:45 -050075 requestBuilder=HttpRequest):
Joe Gregorioabda96f2011-02-11 20:19:33 -050076 """Construct a Resource for interacting with an API.
77
78 Construct a Resource object for interacting with
79 an API. The serviceName and version are the
80 names from the Discovery service.
81
82 Args:
83 serviceName: string, name of the service
84 version: string, the version of the service
85 discoveryServiceUrl: string, a URI Template that points to
86 the location of the discovery service. It should have two
87 parameters {api} and {apiVersion} that when filled in
88 produce an absolute URI to the discovery document for
89 that service.
Joe Gregoriodeeb0202011-02-15 14:49:57 -050090 developerKey: string, key obtained
91 from https://code.google.com/apis/console
Joe Gregorioabda96f2011-02-11 20:19:33 -050092 model: apiclient.Model, converts to and from the wire format
Joe Gregoriodeeb0202011-02-15 14:49:57 -050093 requestBuilder: apiclient.http.HttpRequest, encapsulator for
94 an HTTP request
Joe Gregorioabda96f2011-02-11 20:19:33 -050095
96 Returns:
97 A Resource object with methods for interacting with
98 the service.
99 """
Joe Gregorio48d361f2010-08-18 13:19:21 -0400100 params = {
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400101 'api': serviceName,
Joe Gregorio48d361f2010-08-18 13:19:21 -0400102 'apiVersion': version
103 }
ade@google.com850cf552010-08-20 23:24:56 +0100104
Joe Gregorioc204b642010-09-21 12:01:23 -0400105 if http is None:
106 http = httplib2.Http()
ade@google.com850cf552010-08-20 23:24:56 +0100107 requested_url = uritemplate.expand(discoveryServiceUrl, params)
108 logging.info('URL being requested: %s' % requested_url)
109 resp, content = http.request(requested_url)
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400110 service = simplejson.loads(content)
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400111
Joe Gregorio7c22ab22011-02-16 15:32:39 -0500112 fn = os.path.join(os.path.dirname(__file__), 'contrib',
113 serviceName, 'future.json')
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400114 try:
Joe Gregorio7c22ab22011-02-16 15:32:39 -0500115 f = file(fn, 'r')
Joe Gregorio292b9b82011-01-12 11:36:11 -0500116 future = f.read()
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400117 f.close()
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400118 except IOError:
Joe Gregorio292b9b82011-01-12 11:36:11 -0500119 future = None
120
121 return build_from_document(content, discoveryServiceUrl, future,
122 http, developerKey, model, requestBuilder)
123
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500124
Joe Gregorio292b9b82011-01-12 11:36:11 -0500125def build_from_document(
126 service,
127 base,
128 future=None,
129 http=None,
130 developerKey=None,
Joe Gregoriod433b2a2011-02-22 10:51:51 -0500131 model=None,
Joe Gregorio292b9b82011-01-12 11:36:11 -0500132 requestBuilder=HttpRequest):
Joe Gregorioabda96f2011-02-11 20:19:33 -0500133 """Create a Resource for interacting with an API.
134
135 Same as `build()`, but constructs the Resource object
136 from a discovery document that is it given, as opposed to
137 retrieving one over HTTP.
138
Joe Gregorio292b9b82011-01-12 11:36:11 -0500139 Args:
140 service: string, discovery document
141 base: string, base URI for all HTTP requests, usually the discovery URI
142 future: string, discovery document with future capabilities
143 auth_discovery: dict, information about the authentication the API supports
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500144 http: httplib2.Http, An instance of httplib2.Http or something that acts
145 like it that HTTP requests will be made through.
Joe Gregorio292b9b82011-01-12 11:36:11 -0500146 developerKey: string, Key for controlling API usage, generated
147 from the API Console.
148 model: Model class instance that serializes and
149 de-serializes requests and responses.
150 requestBuilder: Takes an http request and packages it up to be executed.
Joe Gregorioabda96f2011-02-11 20:19:33 -0500151
152 Returns:
153 A Resource object with methods for interacting with
154 the service.
Joe Gregorio292b9b82011-01-12 11:36:11 -0500155 """
156
157 service = simplejson.loads(service)
158 base = urlparse.urljoin(base, service['restBasePath'])
Joe Gregorio292b9b82011-01-12 11:36:11 -0500159 if future:
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500160 future = simplejson.loads(future)
161 auth_discovery = future.get('auth', {})
Joe Gregorio292b9b82011-01-12 11:36:11 -0500162 else:
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400163 future = {}
164 auth_discovery = {}
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400165
Joe Gregoriod433b2a2011-02-22 10:51:51 -0500166 if model is None:
Joe Gregorio266c6442011-02-23 16:08:54 -0500167 features = service.get('features', ['dataWrapper'])
168 model = JsonModel('dataWrapper' in features)
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500169 resource = createResource(http, base, model, requestBuilder, developerKey,
170 service, future)
Joe Gregorio48d361f2010-08-18 13:19:21 -0400171
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500172 def auth_method():
173 """Discovery information about the authentication the API uses."""
174 return auth_discovery
Joe Gregorio48d361f2010-08-18 13:19:21 -0400175
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500176 setattr(resource, 'auth_discovery', auth_method)
Joe Gregorioa2f56e72010-09-09 15:15:56 -0400177
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500178 return resource
Joe Gregorio48d361f2010-08-18 13:19:21 -0400179
180
Joe Gregorio61d7e962011-02-22 22:52:07 -0500181def _cast(value, schema_type):
Joe Gregoriobee86832011-02-22 10:00:19 -0500182 """Convert value to a string based on JSON Schema type.
183
184 See http://tools.ietf.org/html/draft-zyp-json-schema-03 for more details on
185 JSON Schema.
186
187 Args:
188 value: any, the value to convert
189 schema_type: string, the type that value should be interpreted as
190
191 Returns:
192 A string representation of 'value' based on the schema_type.
193 """
194 if schema_type == 'string':
195 return str(value)
196 elif schema_type == 'integer':
197 return str(int(value))
198 elif schema_type == 'number':
199 return str(float(value))
200 elif schema_type == 'boolean':
201 return str(bool(value)).lower()
202 else:
203 return str(value)
204
205
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500206def createResource(http, baseUrl, model, requestBuilder,
Joe Gregorioaf276d22010-12-09 14:26:58 -0500207 developerKey, resourceDesc, futureDesc):
Joe Gregorio48d361f2010-08-18 13:19:21 -0400208
209 class Resource(object):
210 """A class for interacting with a resource."""
211
212 def __init__(self):
213 self._http = http
214 self._baseUrl = baseUrl
215 self._model = model
Joe Gregorio00cf1d92010-09-27 09:22:03 -0400216 self._developerKey = developerKey
Joe Gregorioaf276d22010-12-09 14:26:58 -0500217 self._requestBuilder = requestBuilder
Joe Gregorio48d361f2010-08-18 13:19:21 -0400218
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400219 def createMethod(theclass, methodName, methodDesc, futureDesc):
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400220 pathUrl = methodDesc['restPath']
Joe Gregorio48d361f2010-08-18 13:19:21 -0400221 httpMethod = methodDesc['httpMethod']
Joe Gregorioaf276d22010-12-09 14:26:58 -0500222 methodId = methodDesc['rpcMethod']
Joe Gregorio21f11672010-08-18 17:23:17 -0400223
Joe Gregorioca876e42011-02-22 19:39:42 -0500224 if 'parameters' not in methodDesc:
225 methodDesc['parameters'] = {}
226 for name in STACK_QUERY_PARAMETERS:
227 methodDesc['parameters'][name] = {
228 'type': 'string',
229 'restParameterType': 'query'
230 }
231
ade@google.com850cf552010-08-20 23:24:56 +0100232 if httpMethod in ['PUT', 'POST']:
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500233 methodDesc['parameters']['body'] = {
234 'description': 'The request body.',
Joe Gregorioc2a73932011-02-22 10:17:06 -0500235 'type': 'object',
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500236 }
ade@google.com850cf552010-08-20 23:24:56 +0100237
Joe Gregorioca876e42011-02-22 19:39:42 -0500238 argmap = {} # Map from method parameter name to query parameter name
ade@google.com850cf552010-08-20 23:24:56 +0100239 required_params = [] # Required parameters
Joe Gregorio61d7e962011-02-22 22:52:07 -0500240 repeated_params = [] # Repeated parameters
ade@google.com850cf552010-08-20 23:24:56 +0100241 pattern_params = {} # Parameters that must match a regex
242 query_params = [] # Parameters that will be used in the query string
243 path_params = {} # Parameters that will be used in the base URL
Joe Gregoriobee86832011-02-22 10:00:19 -0500244 param_type = {} # The type of the parameter
Joe Gregorioca876e42011-02-22 19:39:42 -0500245 enum_params = {} # Allowable enumeration values for each parameter
246
247
Joe Gregorio4292c6e2010-09-09 14:32:43 -0400248 if 'parameters' in methodDesc:
249 for arg, desc in methodDesc['parameters'].iteritems():
250 param = key2param(arg)
251 argmap[param] = arg
Joe Gregorio21f11672010-08-18 17:23:17 -0400252
Joe Gregorio4292c6e2010-09-09 14:32:43 -0400253 if desc.get('pattern', ''):
254 pattern_params[param] = desc['pattern']
Joe Gregoriobee86832011-02-22 10:00:19 -0500255 if desc.get('enum', ''):
256 enum_params[param] = desc['enum']
Joe Gregorio4292c6e2010-09-09 14:32:43 -0400257 if desc.get('required', False):
258 required_params.append(param)
Joe Gregorio61d7e962011-02-22 22:52:07 -0500259 if desc.get('repeated', False):
260 repeated_params.append(param)
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400261 if desc.get('restParameterType') == 'query':
Joe Gregorio4292c6e2010-09-09 14:32:43 -0400262 query_params.append(param)
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400263 if desc.get('restParameterType') == 'path':
Joe Gregorio4292c6e2010-09-09 14:32:43 -0400264 path_params[param] = param
Joe Gregoriobee86832011-02-22 10:00:19 -0500265 param_type[param] = desc.get('type', 'string')
Joe Gregorio48d361f2010-08-18 13:19:21 -0400266
Joe Gregoriobc2ff9b2010-11-08 09:20:48 -0500267 for match in URITEMPLATE.finditer(pathUrl):
268 for namematch in VARNAME.finditer(match.group(0)):
269 name = key2param(namematch.group(0))
270 path_params[name] = name
271 if name in query_params:
272 query_params.remove(name)
273
Joe Gregorio48d361f2010-08-18 13:19:21 -0400274 def method(self, **kwargs):
275 for name in kwargs.iterkeys():
Joe Gregorioca876e42011-02-22 19:39:42 -0500276 if name not in argmap:
Joe Gregorio48d361f2010-08-18 13:19:21 -0400277 raise TypeError('Got an unexpected keyword argument "%s"' % name)
Joe Gregorio21f11672010-08-18 17:23:17 -0400278
ade@google.com850cf552010-08-20 23:24:56 +0100279 for name in required_params:
Joe Gregoriofbf9d0d2010-08-18 16:50:47 -0400280 if name not in kwargs:
281 raise TypeError('Missing required parameter "%s"' % name)
Joe Gregorio21f11672010-08-18 17:23:17 -0400282
ade@google.com850cf552010-08-20 23:24:56 +0100283 for name, regex in pattern_params.iteritems():
Joe Gregorio21f11672010-08-18 17:23:17 -0400284 if name in kwargs:
285 if re.match(regex, kwargs[name]) is None:
Joe Gregorio3bbbf662010-08-30 16:41:53 -0400286 raise TypeError(
287 'Parameter "%s" value "%s" does not match the pattern "%s"' %
288 (name, kwargs[name], regex))
Joe Gregorio21f11672010-08-18 17:23:17 -0400289
Joe Gregoriobee86832011-02-22 10:00:19 -0500290 for name, enums in enum_params.iteritems():
291 if name in kwargs:
292 if kwargs[name] not in enums:
293 raise TypeError(
Joe Gregorioca876e42011-02-22 19:39:42 -0500294 'Parameter "%s" value "%s" is not an allowed value in "%s"' %
Joe Gregoriobee86832011-02-22 10:00:19 -0500295 (name, kwargs[name], str(enums)))
296
ade@google.com850cf552010-08-20 23:24:56 +0100297 actual_query_params = {}
298 actual_path_params = {}
Joe Gregorio21f11672010-08-18 17:23:17 -0400299 for key, value in kwargs.iteritems():
Joe Gregorio61d7e962011-02-22 22:52:07 -0500300 to_type = param_type.get(key, 'string')
301 # For repeated parameters we cast each member of the list.
302 if key in repeated_params and type(value) == type([]):
303 cast_value = [_cast(x, to_type) for x in value]
304 else:
305 cast_value = _cast(value, to_type)
ade@google.com850cf552010-08-20 23:24:56 +0100306 if key in query_params:
Joe Gregorio61d7e962011-02-22 22:52:07 -0500307 actual_query_params[argmap[key]] = cast_value
ade@google.com850cf552010-08-20 23:24:56 +0100308 if key in path_params:
Joe Gregorio61d7e962011-02-22 22:52:07 -0500309 actual_path_params[argmap[key]] = cast_value
ade@google.com850cf552010-08-20 23:24:56 +0100310 body_value = kwargs.get('body', None)
Joe Gregorio21f11672010-08-18 17:23:17 -0400311
Joe Gregorio00cf1d92010-09-27 09:22:03 -0400312 if self._developerKey:
313 actual_query_params['key'] = self._developerKey
314
Joe Gregorio48d361f2010-08-18 13:19:21 -0400315 headers = {}
Joe Gregorio3bbbf662010-08-30 16:41:53 -0400316 headers, params, query, body = self._model.request(headers,
317 actual_path_params, actual_query_params, body_value)
Joe Gregorio48d361f2010-08-18 13:19:21 -0400318
Joe Gregorioaf276d22010-12-09 14:26:58 -0500319 # TODO(ade) This exists to fix a bug in V1 of the Buzz discovery
320 # document. Base URLs should not contain any path elements. If they do
321 # then urlparse.urljoin will strip them out This results in an incorrect
322 # URL which returns a 404
ade@google.com7ebb2ca2010-09-29 16:42:15 +0100323 url_result = urlparse.urlsplit(self._baseUrl)
324 new_base_url = url_result.scheme + '://' + url_result.netloc
325
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400326 expanded_url = uritemplate.expand(pathUrl, params)
Joe Gregorioaf276d22010-12-09 14:26:58 -0500327 url = urlparse.urljoin(new_base_url,
328 url_result.path + expanded_url + query)
Joe Gregoriofbf9d0d2010-08-18 16:50:47 -0400329
ade@google.com850cf552010-08-20 23:24:56 +0100330 logging.info('URL being requested: %s' % url)
Joe Gregorioabda96f2011-02-11 20:19:33 -0500331 return self._requestBuilder(self._http,
332 self._model.response,
333 url,
334 method=httpMethod,
335 body=body,
Joe Gregorioaf276d22010-12-09 14:26:58 -0500336 headers=headers,
Joe Gregorioaf276d22010-12-09 14:26:58 -0500337 methodId=methodId)
Joe Gregorio48d361f2010-08-18 13:19:21 -0400338
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500339 docs = [methodDesc.get('description', DEFAULT_METHOD_DOC), '\n\n']
340 if len(argmap) > 0:
Joe Gregorio61d7e962011-02-22 22:52:07 -0500341 docs.append('Args:\n')
Joe Gregorio48d361f2010-08-18 13:19:21 -0400342 for arg in argmap.iterkeys():
Joe Gregorioca876e42011-02-22 19:39:42 -0500343 if arg in STACK_QUERY_PARAMETERS:
344 continue
Joe Gregorio61d7e962011-02-22 22:52:07 -0500345 repeated = ''
346 if arg in repeated_params:
347 repeated = ' (repeated)'
348 required = ''
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400349 if arg in required_params:
Joe Gregorio61d7e962011-02-22 22:52:07 -0500350 required = ' (required)'
Joe Gregorioc2a73932011-02-22 10:17:06 -0500351 paramdesc = methodDesc['parameters'][argmap[arg]]
352 paramdoc = paramdesc.get('description', 'A parameter')
353 paramtype = paramdesc.get('type', 'string')
Joe Gregorio61d7e962011-02-22 22:52:07 -0500354 docs.append(' %s: %s, %s%s%s\n' % (arg, paramtype, paramdoc, required,
355 repeated))
Joe Gregorioc2a73932011-02-22 10:17:06 -0500356 enum = paramdesc.get('enum', [])
357 enumDesc = paramdesc.get('enumDescriptions', [])
358 if enum and enumDesc:
359 docs.append(' Allowed values\n')
360 for (name, desc) in zip(enum, enumDesc):
361 docs.append(' %s - %s\n' % (name, desc))
Joe Gregorio48d361f2010-08-18 13:19:21 -0400362
363 setattr(method, '__doc__', ''.join(docs))
364 setattr(theclass, methodName, method)
365
Joe Gregorioaf276d22010-12-09 14:26:58 -0500366 def createNextMethod(theclass, methodName, methodDesc, futureDesc):
367 methodId = methodDesc['rpcMethod'] + '.next'
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400368
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500369 def methodNext(self, previous):
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400370 """
371 Takes a single argument, 'body', which is the results
372 from the last call, and returns the next set of items
373 in the collection.
374
375 Returns None if there are no more items in
376 the collection.
377 """
Joe Gregorioaf276d22010-12-09 14:26:58 -0500378 if futureDesc['type'] != 'uri':
379 raise UnknownLinkType(futureDesc['type'])
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400380
381 try:
382 p = previous
Joe Gregorioaf276d22010-12-09 14:26:58 -0500383 for key in futureDesc['location']:
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400384 p = p[key]
385 url = p
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400386 except (KeyError, TypeError):
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400387 return None
388
Joe Gregorio00cf1d92010-09-27 09:22:03 -0400389 if self._developerKey:
390 parsed = list(urlparse.urlparse(url))
ade@google.comc5eb46f2010-09-27 23:35:39 +0100391 q = parse_qsl(parsed[4])
Joe Gregorio00cf1d92010-09-27 09:22:03 -0400392 q.append(('key', self._developerKey))
393 parsed[4] = urllib.urlencode(q)
394 url = urlparse.urlunparse(parsed)
395
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400396 headers = {}
397 headers, params, query, body = self._model.request(headers, {}, {}, None)
398
399 logging.info('URL being requested: %s' % url)
400 resp, content = self._http.request(url, method='GET', headers=headers)
401
Joe Gregorioabda96f2011-02-11 20:19:33 -0500402 return self._requestBuilder(self._http,
403 self._model.response,
404 url,
405 method='GET',
Joe Gregorioaf276d22010-12-09 14:26:58 -0500406 headers=headers,
Joe Gregorioaf276d22010-12-09 14:26:58 -0500407 methodId=methodId)
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400408
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500409 setattr(theclass, methodName, methodNext)
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400410
411 # Add basic methods to Resource
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400412 if 'methods' in resourceDesc:
413 for methodName, methodDesc in resourceDesc['methods'].iteritems():
414 if futureDesc:
415 future = futureDesc['methods'].get(methodName, {})
416 else:
417 future = None
418 createMethod(Resource, methodName, methodDesc, future)
419
420 # Add in nested resources
421 if 'resources' in resourceDesc:
Joe Gregorioaf276d22010-12-09 14:26:58 -0500422
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500423 def createResourceMethod(theclass, methodName, methodDesc, futureDesc):
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400424
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500425 def methodResource(self):
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400426 return createResource(self._http, self._baseUrl, self._model,
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500427 self._requestBuilder, self._developerKey,
428 methodDesc, futureDesc)
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400429
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500430 setattr(methodResource, '__doc__', 'A collection resource.')
431 setattr(methodResource, '__is_resource__', True)
432 setattr(theclass, methodName, methodResource)
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400433
434 for methodName, methodDesc in resourceDesc['resources'].iteritems():
435 if futureDesc and 'resources' in futureDesc:
436 future = futureDesc['resources'].get(methodName, {})
437 else:
438 future = {}
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500439 createResourceMethod(Resource, methodName, methodDesc, future)
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400440
441 # Add <m>_next() methods to Resource
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500442 if futureDesc and 'methods' in futureDesc:
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400443 for methodName, methodDesc in futureDesc['methods'].iteritems():
444 if 'next' in methodDesc and methodName in resourceDesc['methods']:
Joe Gregorio61d7e962011-02-22 22:52:07 -0500445 createNextMethod(Resource, methodName + '_next',
Joe Gregorioaf276d22010-12-09 14:26:58 -0500446 resourceDesc['methods'][methodName],
447 methodDesc['next'])
Joe Gregorio48d361f2010-08-18 13:19:21 -0400448
449 return Resource()