blob: b202913a36dc71ac871040b8eb4447b169394694 [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:
167 model = JsonModel('dataWrapper' in service.get('features', []))
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500168 resource = createResource(http, base, model, requestBuilder, developerKey,
169 service, future)
Joe Gregorio48d361f2010-08-18 13:19:21 -0400170
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500171 def auth_method():
172 """Discovery information about the authentication the API uses."""
173 return auth_discovery
Joe Gregorio48d361f2010-08-18 13:19:21 -0400174
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500175 setattr(resource, 'auth_discovery', auth_method)
Joe Gregorioa2f56e72010-09-09 15:15:56 -0400176
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500177 return resource
Joe Gregorio48d361f2010-08-18 13:19:21 -0400178
179
Joe Gregoriobee86832011-02-22 10:00:19 -0500180def _to_string(value, schema_type):
181 """Convert value to a string based on JSON Schema type.
182
183 See http://tools.ietf.org/html/draft-zyp-json-schema-03 for more details on
184 JSON Schema.
185
186 Args:
187 value: any, the value to convert
188 schema_type: string, the type that value should be interpreted as
189
190 Returns:
191 A string representation of 'value' based on the schema_type.
192 """
193 if schema_type == 'string':
194 return str(value)
195 elif schema_type == 'integer':
196 return str(int(value))
197 elif schema_type == 'number':
198 return str(float(value))
199 elif schema_type == 'boolean':
200 return str(bool(value)).lower()
201 else:
202 return str(value)
203
204
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500205def createResource(http, baseUrl, model, requestBuilder,
Joe Gregorioaf276d22010-12-09 14:26:58 -0500206 developerKey, resourceDesc, futureDesc):
Joe Gregorio48d361f2010-08-18 13:19:21 -0400207
208 class Resource(object):
209 """A class for interacting with a resource."""
210
211 def __init__(self):
212 self._http = http
213 self._baseUrl = baseUrl
214 self._model = model
Joe Gregorio00cf1d92010-09-27 09:22:03 -0400215 self._developerKey = developerKey
Joe Gregorioaf276d22010-12-09 14:26:58 -0500216 self._requestBuilder = requestBuilder
Joe Gregorio48d361f2010-08-18 13:19:21 -0400217
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400218 def createMethod(theclass, methodName, methodDesc, futureDesc):
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400219 pathUrl = methodDesc['restPath']
Joe Gregorio48d361f2010-08-18 13:19:21 -0400220 pathUrl = re.sub(r'\{', r'{+', pathUrl)
221 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
240 pattern_params = {} # Parameters that must match a regex
241 query_params = [] # Parameters that will be used in the query string
242 path_params = {} # Parameters that will be used in the base URL
Joe Gregoriobee86832011-02-22 10:00:19 -0500243 param_type = {} # The type of the parameter
Joe Gregorioca876e42011-02-22 19:39:42 -0500244 enum_params = {} # Allowable enumeration values for each parameter
245
246
Joe Gregorio4292c6e2010-09-09 14:32:43 -0400247 if 'parameters' in methodDesc:
248 for arg, desc in methodDesc['parameters'].iteritems():
249 param = key2param(arg)
250 argmap[param] = arg
Joe Gregorio21f11672010-08-18 17:23:17 -0400251
Joe Gregorio4292c6e2010-09-09 14:32:43 -0400252 if desc.get('pattern', ''):
253 pattern_params[param] = desc['pattern']
Joe Gregoriobee86832011-02-22 10:00:19 -0500254 if desc.get('enum', ''):
255 enum_params[param] = desc['enum']
Joe Gregorio4292c6e2010-09-09 14:32:43 -0400256 if desc.get('required', False):
257 required_params.append(param)
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400258 if desc.get('restParameterType') == 'query':
Joe Gregorio4292c6e2010-09-09 14:32:43 -0400259 query_params.append(param)
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400260 if desc.get('restParameterType') == 'path':
Joe Gregorio4292c6e2010-09-09 14:32:43 -0400261 path_params[param] = param
Joe Gregoriobee86832011-02-22 10:00:19 -0500262 param_type[param] = desc.get('type', 'string')
Joe Gregorio48d361f2010-08-18 13:19:21 -0400263
Joe Gregoriobc2ff9b2010-11-08 09:20:48 -0500264 for match in URITEMPLATE.finditer(pathUrl):
265 for namematch in VARNAME.finditer(match.group(0)):
266 name = key2param(namematch.group(0))
267 path_params[name] = name
268 if name in query_params:
269 query_params.remove(name)
270
Joe Gregorio48d361f2010-08-18 13:19:21 -0400271 def method(self, **kwargs):
272 for name in kwargs.iterkeys():
Joe Gregorioca876e42011-02-22 19:39:42 -0500273 if name not in argmap:
Joe Gregorio48d361f2010-08-18 13:19:21 -0400274 raise TypeError('Got an unexpected keyword argument "%s"' % name)
Joe Gregorio21f11672010-08-18 17:23:17 -0400275
ade@google.com850cf552010-08-20 23:24:56 +0100276 for name in required_params:
Joe Gregoriofbf9d0d2010-08-18 16:50:47 -0400277 if name not in kwargs:
278 raise TypeError('Missing required parameter "%s"' % name)
Joe Gregorio21f11672010-08-18 17:23:17 -0400279
ade@google.com850cf552010-08-20 23:24:56 +0100280 for name, regex in pattern_params.iteritems():
Joe Gregorio21f11672010-08-18 17:23:17 -0400281 if name in kwargs:
282 if re.match(regex, kwargs[name]) is None:
Joe Gregorio3bbbf662010-08-30 16:41:53 -0400283 raise TypeError(
284 'Parameter "%s" value "%s" does not match the pattern "%s"' %
285 (name, kwargs[name], regex))
Joe Gregorio21f11672010-08-18 17:23:17 -0400286
Joe Gregoriobee86832011-02-22 10:00:19 -0500287 for name, enums in enum_params.iteritems():
288 if name in kwargs:
289 if kwargs[name] not in enums:
290 raise TypeError(
Joe Gregorioca876e42011-02-22 19:39:42 -0500291 'Parameter "%s" value "%s" is not an allowed value in "%s"' %
Joe Gregoriobee86832011-02-22 10:00:19 -0500292 (name, kwargs[name], str(enums)))
293
ade@google.com850cf552010-08-20 23:24:56 +0100294 actual_query_params = {}
295 actual_path_params = {}
Joe Gregorio21f11672010-08-18 17:23:17 -0400296 for key, value in kwargs.iteritems():
Joe Gregorioca876e42011-02-22 19:39:42 -0500297 value_as_str = _to_string(value, param_type.get(key, 'string'))
ade@google.com850cf552010-08-20 23:24:56 +0100298 if key in query_params:
Joe Gregorioca876e42011-02-22 19:39:42 -0500299 actual_query_params[argmap[key]] = value_as_str
ade@google.com850cf552010-08-20 23:24:56 +0100300 if key in path_params:
Joe Gregorioca876e42011-02-22 19:39:42 -0500301 actual_path_params[argmap[key]] = value_as_str
ade@google.com850cf552010-08-20 23:24:56 +0100302 body_value = kwargs.get('body', None)
Joe Gregorio21f11672010-08-18 17:23:17 -0400303
Joe Gregorio00cf1d92010-09-27 09:22:03 -0400304 if self._developerKey:
305 actual_query_params['key'] = self._developerKey
306
Joe Gregorio48d361f2010-08-18 13:19:21 -0400307 headers = {}
Joe Gregorio3bbbf662010-08-30 16:41:53 -0400308 headers, params, query, body = self._model.request(headers,
309 actual_path_params, actual_query_params, body_value)
Joe Gregorio48d361f2010-08-18 13:19:21 -0400310
Joe Gregorioaf276d22010-12-09 14:26:58 -0500311 # TODO(ade) This exists to fix a bug in V1 of the Buzz discovery
312 # document. Base URLs should not contain any path elements. If they do
313 # then urlparse.urljoin will strip them out This results in an incorrect
314 # URL which returns a 404
ade@google.com7ebb2ca2010-09-29 16:42:15 +0100315 url_result = urlparse.urlsplit(self._baseUrl)
316 new_base_url = url_result.scheme + '://' + url_result.netloc
317
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400318 expanded_url = uritemplate.expand(pathUrl, params)
Joe Gregorioaf276d22010-12-09 14:26:58 -0500319 url = urlparse.urljoin(new_base_url,
320 url_result.path + expanded_url + query)
Joe Gregoriofbf9d0d2010-08-18 16:50:47 -0400321
ade@google.com850cf552010-08-20 23:24:56 +0100322 logging.info('URL being requested: %s' % url)
Joe Gregorioabda96f2011-02-11 20:19:33 -0500323 return self._requestBuilder(self._http,
324 self._model.response,
325 url,
326 method=httpMethod,
327 body=body,
Joe Gregorioaf276d22010-12-09 14:26:58 -0500328 headers=headers,
Joe Gregorioaf276d22010-12-09 14:26:58 -0500329 methodId=methodId)
Joe Gregorio48d361f2010-08-18 13:19:21 -0400330
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500331 docs = [methodDesc.get('description', DEFAULT_METHOD_DOC), '\n\n']
332 if len(argmap) > 0:
333 docs.append("Args:\n")
Joe Gregorio48d361f2010-08-18 13:19:21 -0400334 for arg in argmap.iterkeys():
Joe Gregorioca876e42011-02-22 19:39:42 -0500335 if arg in STACK_QUERY_PARAMETERS:
336 continue
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500337 required = ""
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400338 if arg in required_params:
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500339 required = " (required)"
Joe Gregorioc2a73932011-02-22 10:17:06 -0500340 paramdesc = methodDesc['parameters'][argmap[arg]]
341 paramdoc = paramdesc.get('description', 'A parameter')
342 paramtype = paramdesc.get('type', 'string')
343 docs.append(' %s: %s, %s%s\n' % (arg, paramtype, paramdoc, required))
344 enum = paramdesc.get('enum', [])
345 enumDesc = paramdesc.get('enumDescriptions', [])
346 if enum and enumDesc:
347 docs.append(' Allowed values\n')
348 for (name, desc) in zip(enum, enumDesc):
349 docs.append(' %s - %s\n' % (name, desc))
Joe Gregorio48d361f2010-08-18 13:19:21 -0400350
351 setattr(method, '__doc__', ''.join(docs))
352 setattr(theclass, methodName, method)
353
Joe Gregorioaf276d22010-12-09 14:26:58 -0500354 def createNextMethod(theclass, methodName, methodDesc, futureDesc):
355 methodId = methodDesc['rpcMethod'] + '.next'
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400356
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500357 def methodNext(self, previous):
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400358 """
359 Takes a single argument, 'body', which is the results
360 from the last call, and returns the next set of items
361 in the collection.
362
363 Returns None if there are no more items in
364 the collection.
365 """
Joe Gregorioaf276d22010-12-09 14:26:58 -0500366 if futureDesc['type'] != 'uri':
367 raise UnknownLinkType(futureDesc['type'])
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400368
369 try:
370 p = previous
Joe Gregorioaf276d22010-12-09 14:26:58 -0500371 for key in futureDesc['location']:
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400372 p = p[key]
373 url = p
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400374 except (KeyError, TypeError):
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400375 return None
376
Joe Gregorio00cf1d92010-09-27 09:22:03 -0400377 if self._developerKey:
378 parsed = list(urlparse.urlparse(url))
ade@google.comc5eb46f2010-09-27 23:35:39 +0100379 q = parse_qsl(parsed[4])
Joe Gregorio00cf1d92010-09-27 09:22:03 -0400380 q.append(('key', self._developerKey))
381 parsed[4] = urllib.urlencode(q)
382 url = urlparse.urlunparse(parsed)
383
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400384 headers = {}
385 headers, params, query, body = self._model.request(headers, {}, {}, None)
386
387 logging.info('URL being requested: %s' % url)
388 resp, content = self._http.request(url, method='GET', headers=headers)
389
Joe Gregorioabda96f2011-02-11 20:19:33 -0500390 return self._requestBuilder(self._http,
391 self._model.response,
392 url,
393 method='GET',
Joe Gregorioaf276d22010-12-09 14:26:58 -0500394 headers=headers,
Joe Gregorioaf276d22010-12-09 14:26:58 -0500395 methodId=methodId)
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400396
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500397 setattr(theclass, methodName, methodNext)
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400398
399 # Add basic methods to Resource
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400400 if 'methods' in resourceDesc:
401 for methodName, methodDesc in resourceDesc['methods'].iteritems():
402 if futureDesc:
403 future = futureDesc['methods'].get(methodName, {})
404 else:
405 future = None
406 createMethod(Resource, methodName, methodDesc, future)
407
408 # Add in nested resources
409 if 'resources' in resourceDesc:
Joe Gregorioaf276d22010-12-09 14:26:58 -0500410
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500411 def createResourceMethod(theclass, methodName, methodDesc, futureDesc):
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400412
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500413 def methodResource(self):
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400414 return createResource(self._http, self._baseUrl, self._model,
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500415 self._requestBuilder, self._developerKey,
416 methodDesc, futureDesc)
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400417
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500418 setattr(methodResource, '__doc__', 'A collection resource.')
419 setattr(methodResource, '__is_resource__', True)
420 setattr(theclass, methodName, methodResource)
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400421
422 for methodName, methodDesc in resourceDesc['resources'].iteritems():
423 if futureDesc and 'resources' in futureDesc:
424 future = futureDesc['resources'].get(methodName, {})
425 else:
426 future = {}
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500427 createResourceMethod(Resource, methodName, methodDesc, future)
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400428
429 # Add <m>_next() methods to Resource
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500430 if futureDesc and 'methods' in futureDesc:
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400431 for methodName, methodDesc in futureDesc['methods'].iteritems():
432 if 'next' in methodDesc and methodName in resourceDesc['methods']:
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500433 createNextMethod(Resource, methodName + "_next",
Joe Gregorioaf276d22010-12-09 14:26:58 -0500434 resourceDesc['methods'][methodName],
435 methodDesc['next'])
Joe Gregorio48d361f2010-08-18 13:19:21 -0400436
437 return Resource()