blob: 2a53b0d98615a2a06d38dc7efb5f17c68752d8ed [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
Joe Gregorio3c676f92011-07-25 10:38:14 -040025import copy
Joe Gregorio48d361f2010-08-18 13:19:21 -040026import httplib2
ade@google.com850cf552010-08-20 23:24:56 +010027import logging
Joe Gregorio6d5e94f2010-08-25 23:49:30 -040028import os
Joe Gregorio48d361f2010-08-18 13:19:21 -040029import re
Joe Gregorio48d361f2010-08-18 13:19:21 -040030import uritemplate
Joe Gregoriofe695fb2010-08-30 12:04:04 -040031import urllib
Joe Gregorio6d5e94f2010-08-25 23:49:30 -040032import urlparse
Joe Gregoriofdf7c802011-06-30 12:33:38 -040033import mimeparse
Joe Gregorio922b78c2011-05-26 21:36:34 -040034import mimetypes
35
ade@google.comc5eb46f2010-09-27 23:35:39 +010036try:
37 from urlparse import parse_qsl
38except ImportError:
39 from cgi import parse_qsl
Joe Gregorioaf276d22010-12-09 14:26:58 -050040
Joe Gregorio034e7002010-12-15 08:45:03 -050041from anyjson import simplejson
Joe Gregorio922b78c2011-05-26 21:36:34 -040042from email.mime.multipart import MIMEMultipart
43from email.mime.nonmultipart import MIMENonMultipart
Joe Gregorioc0e0fe92011-03-04 16:16:55 -050044from errors import HttpError
Joe Gregorio49396552011-03-08 10:39:00 -050045from errors import InvalidJsonError
Joe Gregoriofdf7c802011-06-30 12:33:38 -040046from errors import MediaUploadSizeError
47from errors import UnacceptableMimeTypeError
Joe Gregoriodae2f552011-11-21 08:16:56 -050048from errors import UnknownApiNameOrVersion
Joe Gregorio922b78c2011-05-26 21:36:34 -040049from errors import UnknownLinkType
50from http import HttpRequest
51from model import JsonModel
Joe Gregorio48d361f2010-08-18 13:19:21 -040052
Joe Gregoriobc2ff9b2010-11-08 09:20:48 -050053URITEMPLATE = re.compile('{[^}]*}')
54VARNAME = re.compile('[a-zA-Z0-9_-]+')
Joe Gregorio6a63a762011-05-02 22:36:05 -040055DISCOVERY_URI = ('https://www.googleapis.com/discovery/v1/apis/'
56 '{api}/{apiVersion}/rest')
Joe Gregorioc3fae8a2011-02-18 14:19:50 -050057DEFAULT_METHOD_DOC = 'A description of how to use this function'
Joe Gregorioca876e42011-02-22 19:39:42 -050058
59# Query parameters that work, but don't appear in discovery
Joe Gregorio06d852b2011-03-25 15:03:10 -040060STACK_QUERY_PARAMETERS = ['trace', 'fields', 'pp', 'prettyPrint', 'userIp',
Joe Gregorio3eecaa92011-05-17 13:40:12 -040061 'userip', 'strict']
Joe Gregorio48d361f2010-08-18 13:19:21 -040062
Joe Gregorio562b7312011-09-15 09:06:38 -040063RESERVED_WORDS = ['and', 'assert', 'break', 'class', 'continue', 'def', 'del',
Joe Gregoriod92897c2011-07-07 11:44:56 -040064 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from',
65 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or',
66 'pass', 'print', 'raise', 'return', 'try', 'while' ]
67
Joe Gregorio562b7312011-09-15 09:06:38 -040068
Joe Gregoriod92897c2011-07-07 11:44:56 -040069def _fix_method_name(name):
70 if name in RESERVED_WORDS:
71 return name + '_'
72 else:
73 return name
Joe Gregorio48d361f2010-08-18 13:19:21 -040074
Joe Gregorioa98733f2011-09-16 10:12:28 -040075
Joe Gregorio922b78c2011-05-26 21:36:34 -040076def _write_headers(self):
77 # Utility no-op method for multipart media handling
78 pass
79
80
Joe Gregorioa98733f2011-09-16 10:12:28 -040081def _add_query_parameter(url, name, value):
82 """Adds a query parameter to a url
83
84 Args:
85 url: string, url to add the query parameter to.
86 name: string, query parameter name.
87 value: string, query parameter value.
88
89 Returns:
90 Updated query parameter. Does not update the url if value is None.
91 """
92 if value is None:
93 return url
94 else:
95 parsed = list(urlparse.urlparse(url))
96 q = parse_qsl(parsed[4])
97 q.append((name, value))
98 parsed[4] = urllib.urlencode(q)
99 return urlparse.urlunparse(parsed)
100
101
Joe Gregorio48d361f2010-08-18 13:19:21 -0400102def key2param(key):
Joe Gregorio7c22ab22011-02-16 15:32:39 -0500103 """Converts key names into parameter names.
104
105 For example, converting "max-results" -> "max_results"
Joe Gregorio48d361f2010-08-18 13:19:21 -0400106 """
107 result = []
108 key = list(key)
109 if not key[0].isalpha():
110 result.append('x')
111 for c in key:
112 if c.isalnum():
113 result.append(c)
114 else:
115 result.append('_')
116
117 return ''.join(result)
118
119
Joe Gregorioaf276d22010-12-09 14:26:58 -0500120def build(serviceName, version,
Joe Gregorio3fada332011-01-07 17:07:45 -0500121 http=None,
122 discoveryServiceUrl=DISCOVERY_URI,
123 developerKey=None,
Joe Gregoriod433b2a2011-02-22 10:51:51 -0500124 model=None,
Joe Gregorio3fada332011-01-07 17:07:45 -0500125 requestBuilder=HttpRequest):
Joe Gregorioabda96f2011-02-11 20:19:33 -0500126 """Construct a Resource for interacting with an API.
127
128 Construct a Resource object for interacting with
129 an API. The serviceName and version are the
130 names from the Discovery service.
131
132 Args:
133 serviceName: string, name of the service
134 version: string, the version of the service
135 discoveryServiceUrl: string, a URI Template that points to
136 the location of the discovery service. It should have two
137 parameters {api} and {apiVersion} that when filled in
138 produce an absolute URI to the discovery document for
139 that service.
Joe Gregoriodeeb0202011-02-15 14:49:57 -0500140 developerKey: string, key obtained
141 from https://code.google.com/apis/console
Joe Gregorioabda96f2011-02-11 20:19:33 -0500142 model: apiclient.Model, converts to and from the wire format
Joe Gregoriodeeb0202011-02-15 14:49:57 -0500143 requestBuilder: apiclient.http.HttpRequest, encapsulator for
144 an HTTP request
Joe Gregorioabda96f2011-02-11 20:19:33 -0500145
146 Returns:
147 A Resource object with methods for interacting with
148 the service.
149 """
Joe Gregorio48d361f2010-08-18 13:19:21 -0400150 params = {
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400151 'api': serviceName,
Joe Gregorio48d361f2010-08-18 13:19:21 -0400152 'apiVersion': version
153 }
ade@google.com850cf552010-08-20 23:24:56 +0100154
Joe Gregorioc204b642010-09-21 12:01:23 -0400155 if http is None:
156 http = httplib2.Http()
Joe Gregorioa98733f2011-09-16 10:12:28 -0400157
ade@google.com850cf552010-08-20 23:24:56 +0100158 requested_url = uritemplate.expand(discoveryServiceUrl, params)
Joe Gregorio583d9e42011-09-16 15:54:15 -0400159
160 # REMOTE_ADDR is defined by the CGI spec [RFC3875] as the environment variable
161 # that contains the network address of the client sending the request. If it
162 # exists then add that to the request for the discovery document to avoid
163 # exceeding the quota on discovery requests.
164 if 'REMOTE_ADDR' in os.environ:
165 requested_url = _add_query_parameter(requested_url, 'userIp',
166 os.environ['REMOTE_ADDR'])
ade@google.com850cf552010-08-20 23:24:56 +0100167 logging.info('URL being requested: %s' % requested_url)
Joe Gregorioa98733f2011-09-16 10:12:28 -0400168
ade@google.com850cf552010-08-20 23:24:56 +0100169 resp, content = http.request(requested_url)
Joe Gregorioa98733f2011-09-16 10:12:28 -0400170
Joe Gregorio8b4df3f2011-11-18 15:44:48 -0500171 if resp.status == 404:
Joe Gregoriodae2f552011-11-21 08:16:56 -0500172 raise UnknownApiNameOrVersion("name: %s version: %s" % (serviceName,
Joe Gregorio8b4df3f2011-11-18 15:44:48 -0500173 version))
Joe Gregorioa98733f2011-09-16 10:12:28 -0400174 if resp.status >= 400:
Joe Gregorio49396552011-03-08 10:39:00 -0500175 raise HttpError(resp, content, requested_url)
Joe Gregorioa98733f2011-09-16 10:12:28 -0400176
Joe Gregorioc0e0fe92011-03-04 16:16:55 -0500177 try:
178 service = simplejson.loads(content)
179 except ValueError, e:
Joe Gregorio205e73a2011-03-12 09:55:31 -0500180 logging.error('Failed to parse as JSON: ' + content)
Joe Gregorio49396552011-03-08 10:39:00 -0500181 raise InvalidJsonError()
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400182
Joe Gregorioa98733f2011-09-16 10:12:28 -0400183 filename = os.path.join(os.path.dirname(__file__), 'contrib',
Joe Gregorio7c22ab22011-02-16 15:32:39 -0500184 serviceName, 'future.json')
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400185 try:
Joe Gregorioa98733f2011-09-16 10:12:28 -0400186 f = file(filename, 'r')
Joe Gregorio292b9b82011-01-12 11:36:11 -0500187 future = f.read()
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400188 f.close()
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400189 except IOError:
Joe Gregorio292b9b82011-01-12 11:36:11 -0500190 future = None
191
192 return build_from_document(content, discoveryServiceUrl, future,
193 http, developerKey, model, requestBuilder)
194
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500195
Joe Gregorio292b9b82011-01-12 11:36:11 -0500196def build_from_document(
197 service,
198 base,
199 future=None,
200 http=None,
201 developerKey=None,
Joe Gregoriod433b2a2011-02-22 10:51:51 -0500202 model=None,
Joe Gregorio292b9b82011-01-12 11:36:11 -0500203 requestBuilder=HttpRequest):
Joe Gregorioabda96f2011-02-11 20:19:33 -0500204 """Create a Resource for interacting with an API.
205
206 Same as `build()`, but constructs the Resource object
207 from a discovery document that is it given, as opposed to
208 retrieving one over HTTP.
209
Joe Gregorio292b9b82011-01-12 11:36:11 -0500210 Args:
211 service: string, discovery document
212 base: string, base URI for all HTTP requests, usually the discovery URI
213 future: string, discovery document with future capabilities
214 auth_discovery: dict, information about the authentication the API supports
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500215 http: httplib2.Http, An instance of httplib2.Http or something that acts
216 like it that HTTP requests will be made through.
Joe Gregorio292b9b82011-01-12 11:36:11 -0500217 developerKey: string, Key for controlling API usage, generated
218 from the API Console.
219 model: Model class instance that serializes and
220 de-serializes requests and responses.
221 requestBuilder: Takes an http request and packages it up to be executed.
Joe Gregorioabda96f2011-02-11 20:19:33 -0500222
223 Returns:
224 A Resource object with methods for interacting with
225 the service.
Joe Gregorio292b9b82011-01-12 11:36:11 -0500226 """
227
228 service = simplejson.loads(service)
Joe Gregorio6a63a762011-05-02 22:36:05 -0400229 base = urlparse.urljoin(base, service['basePath'])
Joe Gregorio292b9b82011-01-12 11:36:11 -0500230 if future:
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500231 future = simplejson.loads(future)
232 auth_discovery = future.get('auth', {})
Joe Gregorio292b9b82011-01-12 11:36:11 -0500233 else:
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400234 future = {}
235 auth_discovery = {}
Joe Gregorio3c676f92011-07-25 10:38:14 -0400236 schema = service.get('schemas', {})
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400237
Joe Gregoriod433b2a2011-02-22 10:51:51 -0500238 if model is None:
Joe Gregoriof863f7a2011-02-24 03:24:44 -0500239 features = service.get('features', [])
Joe Gregorio266c6442011-02-23 16:08:54 -0500240 model = JsonModel('dataWrapper' in features)
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500241 resource = createResource(http, base, model, requestBuilder, developerKey,
Joe Gregorio3c676f92011-07-25 10:38:14 -0400242 service, future, schema)
Joe Gregorio48d361f2010-08-18 13:19:21 -0400243
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500244 def auth_method():
245 """Discovery information about the authentication the API uses."""
246 return auth_discovery
Joe Gregorio48d361f2010-08-18 13:19:21 -0400247
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500248 setattr(resource, 'auth_discovery', auth_method)
Joe Gregorioa2f56e72010-09-09 15:15:56 -0400249
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500250 return resource
Joe Gregorio48d361f2010-08-18 13:19:21 -0400251
252
Joe Gregorio61d7e962011-02-22 22:52:07 -0500253def _cast(value, schema_type):
Joe Gregoriobee86832011-02-22 10:00:19 -0500254 """Convert value to a string based on JSON Schema type.
255
256 See http://tools.ietf.org/html/draft-zyp-json-schema-03 for more details on
257 JSON Schema.
258
259 Args:
260 value: any, the value to convert
261 schema_type: string, the type that value should be interpreted as
262
263 Returns:
264 A string representation of 'value' based on the schema_type.
265 """
266 if schema_type == 'string':
Joe Gregoriof863f7a2011-02-24 03:24:44 -0500267 if type(value) == type('') or type(value) == type(u''):
268 return value
269 else:
270 return str(value)
Joe Gregoriobee86832011-02-22 10:00:19 -0500271 elif schema_type == 'integer':
272 return str(int(value))
273 elif schema_type == 'number':
274 return str(float(value))
275 elif schema_type == 'boolean':
276 return str(bool(value)).lower()
277 else:
Joe Gregoriof863f7a2011-02-24 03:24:44 -0500278 if type(value) == type('') or type(value) == type(u''):
279 return value
280 else:
281 return str(value)
Joe Gregoriobee86832011-02-22 10:00:19 -0500282
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400283MULTIPLIERS = {
Joe Gregorio562b7312011-09-15 09:06:38 -0400284 "KB": 2 ** 10,
285 "MB": 2 ** 20,
286 "GB": 2 ** 30,
287 "TB": 2 ** 40,
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400288 }
289
Joe Gregorioa98733f2011-09-16 10:12:28 -0400290
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400291def _media_size_to_long(maxSize):
292 """Convert a string media size, such as 10GB or 3TB into an integer."""
Joe Gregorio84d3c1f2011-07-25 10:39:45 -0400293 if len(maxSize) < 2:
294 return 0
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400295 units = maxSize[-2:].upper()
296 multiplier = MULTIPLIERS.get(units, 0)
297 if multiplier:
Joe Gregorio562b7312011-09-15 09:06:38 -0400298 return int(maxSize[:-2]) * multiplier
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400299 else:
300 return int(maxSize)
301
Joe Gregoriobee86832011-02-22 10:00:19 -0500302
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500303def createResource(http, baseUrl, model, requestBuilder,
Joe Gregorio3c676f92011-07-25 10:38:14 -0400304 developerKey, resourceDesc, futureDesc, schema):
Joe Gregorio48d361f2010-08-18 13:19:21 -0400305
306 class Resource(object):
307 """A class for interacting with a resource."""
308
309 def __init__(self):
310 self._http = http
311 self._baseUrl = baseUrl
312 self._model = model
Joe Gregorio00cf1d92010-09-27 09:22:03 -0400313 self._developerKey = developerKey
Joe Gregorioaf276d22010-12-09 14:26:58 -0500314 self._requestBuilder = requestBuilder
Joe Gregorio48d361f2010-08-18 13:19:21 -0400315
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400316 def createMethod(theclass, methodName, methodDesc, futureDesc):
Joe Gregoriod92897c2011-07-07 11:44:56 -0400317 methodName = _fix_method_name(methodName)
Joe Gregorio6a63a762011-05-02 22:36:05 -0400318 pathUrl = methodDesc['path']
Joe Gregorio48d361f2010-08-18 13:19:21 -0400319 httpMethod = methodDesc['httpMethod']
Joe Gregorio6a63a762011-05-02 22:36:05 -0400320 methodId = methodDesc['id']
Joe Gregorio21f11672010-08-18 17:23:17 -0400321
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400322 mediaPathUrl = None
323 accept = []
324 maxSize = 0
325 if 'mediaUpload' in methodDesc:
326 mediaUpload = methodDesc['mediaUpload']
327 mediaPathUrl = mediaUpload['protocols']['simple']['path']
328 accept = mediaUpload['accept']
Joe Gregorio84d3c1f2011-07-25 10:39:45 -0400329 maxSize = _media_size_to_long(mediaUpload.get('maxSize', ''))
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400330
Joe Gregorioca876e42011-02-22 19:39:42 -0500331 if 'parameters' not in methodDesc:
332 methodDesc['parameters'] = {}
333 for name in STACK_QUERY_PARAMETERS:
334 methodDesc['parameters'][name] = {
335 'type': 'string',
Joe Gregorio6a63a762011-05-02 22:36:05 -0400336 'location': 'query'
Joe Gregorioca876e42011-02-22 19:39:42 -0500337 }
338
Joe Gregoriof4153422011-03-18 22:45:18 -0400339 if httpMethod in ['PUT', 'POST', 'PATCH']:
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500340 methodDesc['parameters']['body'] = {
341 'description': 'The request body.',
Joe Gregorioc2a73932011-02-22 10:17:06 -0500342 'type': 'object',
Joe Gregorio1ae3e742011-02-25 15:17:14 -0500343 'required': True,
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500344 }
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400345 if 'mediaUpload' in methodDesc:
346 methodDesc['parameters']['media_body'] = {
347 'description': 'The filename of the media request body.',
348 'type': 'string',
349 'required': False,
350 }
351 methodDesc['parameters']['body']['required'] = False
ade@google.com850cf552010-08-20 23:24:56 +0100352
Joe Gregorioca876e42011-02-22 19:39:42 -0500353 argmap = {} # Map from method parameter name to query parameter name
ade@google.com850cf552010-08-20 23:24:56 +0100354 required_params = [] # Required parameters
Joe Gregorio61d7e962011-02-22 22:52:07 -0500355 repeated_params = [] # Repeated parameters
ade@google.com850cf552010-08-20 23:24:56 +0100356 pattern_params = {} # Parameters that must match a regex
357 query_params = [] # Parameters that will be used in the query string
358 path_params = {} # Parameters that will be used in the base URL
Joe Gregoriobee86832011-02-22 10:00:19 -0500359 param_type = {} # The type of the parameter
Joe Gregorioca876e42011-02-22 19:39:42 -0500360 enum_params = {} # Allowable enumeration values for each parameter
361
362
Joe Gregorio4292c6e2010-09-09 14:32:43 -0400363 if 'parameters' in methodDesc:
364 for arg, desc in methodDesc['parameters'].iteritems():
365 param = key2param(arg)
366 argmap[param] = arg
Joe Gregorio21f11672010-08-18 17:23:17 -0400367
Joe Gregorio4292c6e2010-09-09 14:32:43 -0400368 if desc.get('pattern', ''):
369 pattern_params[param] = desc['pattern']
Joe Gregoriobee86832011-02-22 10:00:19 -0500370 if desc.get('enum', ''):
371 enum_params[param] = desc['enum']
Joe Gregorio4292c6e2010-09-09 14:32:43 -0400372 if desc.get('required', False):
373 required_params.append(param)
Joe Gregorio61d7e962011-02-22 22:52:07 -0500374 if desc.get('repeated', False):
375 repeated_params.append(param)
Joe Gregorio6a63a762011-05-02 22:36:05 -0400376 if desc.get('location') == 'query':
Joe Gregorio4292c6e2010-09-09 14:32:43 -0400377 query_params.append(param)
Joe Gregorio6a63a762011-05-02 22:36:05 -0400378 if desc.get('location') == 'path':
Joe Gregorio4292c6e2010-09-09 14:32:43 -0400379 path_params[param] = param
Joe Gregoriobee86832011-02-22 10:00:19 -0500380 param_type[param] = desc.get('type', 'string')
Joe Gregorio48d361f2010-08-18 13:19:21 -0400381
Joe Gregoriobc2ff9b2010-11-08 09:20:48 -0500382 for match in URITEMPLATE.finditer(pathUrl):
383 for namematch in VARNAME.finditer(match.group(0)):
384 name = key2param(namematch.group(0))
385 path_params[name] = name
386 if name in query_params:
387 query_params.remove(name)
388
Joe Gregorio48d361f2010-08-18 13:19:21 -0400389 def method(self, **kwargs):
390 for name in kwargs.iterkeys():
Joe Gregorioca876e42011-02-22 19:39:42 -0500391 if name not in argmap:
Joe Gregorio48d361f2010-08-18 13:19:21 -0400392 raise TypeError('Got an unexpected keyword argument "%s"' % name)
Joe Gregorio21f11672010-08-18 17:23:17 -0400393
ade@google.com850cf552010-08-20 23:24:56 +0100394 for name in required_params:
Joe Gregoriofbf9d0d2010-08-18 16:50:47 -0400395 if name not in kwargs:
396 raise TypeError('Missing required parameter "%s"' % name)
Joe Gregorio21f11672010-08-18 17:23:17 -0400397
ade@google.com850cf552010-08-20 23:24:56 +0100398 for name, regex in pattern_params.iteritems():
Joe Gregorio21f11672010-08-18 17:23:17 -0400399 if name in kwargs:
Joe Gregorio6804c7a2011-11-18 14:30:32 -0500400 if isinstance(kwargs[name], basestring):
401 pvalues = [kwargs[name]]
402 else:
403 pvalues = kwargs[name]
404 for pvalue in pvalues:
405 if re.match(regex, pvalue) is None:
406 raise TypeError(
407 'Parameter "%s" value "%s" does not match the pattern "%s"' %
408 (name, pvalue, regex))
Joe Gregorio21f11672010-08-18 17:23:17 -0400409
Joe Gregoriobee86832011-02-22 10:00:19 -0500410 for name, enums in enum_params.iteritems():
411 if name in kwargs:
412 if kwargs[name] not in enums:
413 raise TypeError(
Joe Gregorioca876e42011-02-22 19:39:42 -0500414 'Parameter "%s" value "%s" is not an allowed value in "%s"' %
Joe Gregoriobee86832011-02-22 10:00:19 -0500415 (name, kwargs[name], str(enums)))
416
ade@google.com850cf552010-08-20 23:24:56 +0100417 actual_query_params = {}
418 actual_path_params = {}
Joe Gregorio21f11672010-08-18 17:23:17 -0400419 for key, value in kwargs.iteritems():
Joe Gregorio61d7e962011-02-22 22:52:07 -0500420 to_type = param_type.get(key, 'string')
421 # For repeated parameters we cast each member of the list.
422 if key in repeated_params and type(value) == type([]):
423 cast_value = [_cast(x, to_type) for x in value]
424 else:
425 cast_value = _cast(value, to_type)
ade@google.com850cf552010-08-20 23:24:56 +0100426 if key in query_params:
Joe Gregorio61d7e962011-02-22 22:52:07 -0500427 actual_query_params[argmap[key]] = cast_value
ade@google.com850cf552010-08-20 23:24:56 +0100428 if key in path_params:
Joe Gregorio61d7e962011-02-22 22:52:07 -0500429 actual_path_params[argmap[key]] = cast_value
ade@google.com850cf552010-08-20 23:24:56 +0100430 body_value = kwargs.get('body', None)
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400431 media_filename = kwargs.get('media_body', None)
Joe Gregorio21f11672010-08-18 17:23:17 -0400432
Joe Gregorio00cf1d92010-09-27 09:22:03 -0400433 if self._developerKey:
434 actual_query_params['key'] = self._developerKey
435
Joe Gregorio48d361f2010-08-18 13:19:21 -0400436 headers = {}
Joe Gregorio3bbbf662010-08-30 16:41:53 -0400437 headers, params, query, body = self._model.request(headers,
438 actual_path_params, actual_query_params, body_value)
Joe Gregorio48d361f2010-08-18 13:19:21 -0400439
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400440 expanded_url = uritemplate.expand(pathUrl, params)
Joe Gregorio922b78c2011-05-26 21:36:34 -0400441 url = urlparse.urljoin(self._baseUrl, expanded_url + query)
442
443 if media_filename:
444 (media_mime_type, encoding) = mimetypes.guess_type(media_filename)
445 if media_mime_type is None:
446 raise UnknownFileType(media_filename)
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400447 if not mimeparse.best_match([media_mime_type], ','.join(accept)):
448 raise UnacceptableMimeTypeError(media_mime_type)
Joe Gregorio922b78c2011-05-26 21:36:34 -0400449
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400450 # Check the maxSize
451 if maxSize > 0 and os.path.getsize(media_filename) > maxSize:
452 raise MediaUploadSizeError(media_filename)
453
454 # Use the media path uri for media uploads
455 expanded_url = uritemplate.expand(mediaPathUrl, params)
456 url = urlparse.urljoin(self._baseUrl, expanded_url + query)
Joe Gregorio922b78c2011-05-26 21:36:34 -0400457
458 if body is None:
459 headers['content-type'] = media_mime_type
460 # make the body the contents of the file
461 f = file(media_filename, 'rb')
462 body = f.read()
463 f.close()
464 else:
465 msgRoot = MIMEMultipart('related')
466 # msgRoot should not write out it's own headers
467 setattr(msgRoot, '_write_headers', lambda self: None)
468
469 # attach the body as one part
470 msg = MIMENonMultipart(*headers['content-type'].split('/'))
471 msg.set_payload(body)
472 msgRoot.attach(msg)
473
474 # attach the media as the second part
475 msg = MIMENonMultipart(*media_mime_type.split('/'))
476 msg['Content-Transfer-Encoding'] = 'binary'
477
478 f = file(media_filename, 'rb')
479 msg.set_payload(f.read())
480 f.close()
481 msgRoot.attach(msg)
482
483 body = msgRoot.as_string()
484
485 # must appear after the call to as_string() to get the right boundary
486 headers['content-type'] = ('multipart/related; '
487 'boundary="%s"') % msgRoot.get_boundary()
Joe Gregoriofbf9d0d2010-08-18 16:50:47 -0400488
ade@google.com850cf552010-08-20 23:24:56 +0100489 logging.info('URL being requested: %s' % url)
Joe Gregorioabda96f2011-02-11 20:19:33 -0500490 return self._requestBuilder(self._http,
491 self._model.response,
492 url,
493 method=httpMethod,
494 body=body,
Joe Gregorioaf276d22010-12-09 14:26:58 -0500495 headers=headers,
Joe Gregorioaf276d22010-12-09 14:26:58 -0500496 methodId=methodId)
Joe Gregorio48d361f2010-08-18 13:19:21 -0400497
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500498 docs = [methodDesc.get('description', DEFAULT_METHOD_DOC), '\n\n']
499 if len(argmap) > 0:
Joe Gregorio61d7e962011-02-22 22:52:07 -0500500 docs.append('Args:\n')
Joe Gregorio48d361f2010-08-18 13:19:21 -0400501 for arg in argmap.iterkeys():
Joe Gregorioca876e42011-02-22 19:39:42 -0500502 if arg in STACK_QUERY_PARAMETERS:
503 continue
Joe Gregorio61d7e962011-02-22 22:52:07 -0500504 repeated = ''
505 if arg in repeated_params:
506 repeated = ' (repeated)'
507 required = ''
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400508 if arg in required_params:
Joe Gregorio61d7e962011-02-22 22:52:07 -0500509 required = ' (required)'
Joe Gregorioc2a73932011-02-22 10:17:06 -0500510 paramdesc = methodDesc['parameters'][argmap[arg]]
511 paramdoc = paramdesc.get('description', 'A parameter')
512 paramtype = paramdesc.get('type', 'string')
Joe Gregorio61d7e962011-02-22 22:52:07 -0500513 docs.append(' %s: %s, %s%s%s\n' % (arg, paramtype, paramdoc, required,
514 repeated))
Joe Gregorioc2a73932011-02-22 10:17:06 -0500515 enum = paramdesc.get('enum', [])
516 enumDesc = paramdesc.get('enumDescriptions', [])
517 if enum and enumDesc:
518 docs.append(' Allowed values\n')
519 for (name, desc) in zip(enum, enumDesc):
520 docs.append(' %s - %s\n' % (name, desc))
Joe Gregorio48d361f2010-08-18 13:19:21 -0400521
522 setattr(method, '__doc__', ''.join(docs))
523 setattr(theclass, methodName, method)
524
Joe Gregorio3c676f92011-07-25 10:38:14 -0400525 def createNextMethodFromFuture(theclass, methodName, methodDesc, futureDesc):
Joe Gregorioa98733f2011-09-16 10:12:28 -0400526 """ This is a legacy method, as only Buzz and Moderator use the future.json
527 functionality for generating _next methods. It will be kept around as long
528 as those API versions are around, but no new APIs should depend upon it.
529 """
Joe Gregoriod92897c2011-07-07 11:44:56 -0400530 methodName = _fix_method_name(methodName)
Joe Gregorio6a63a762011-05-02 22:36:05 -0400531 methodId = methodDesc['id'] + '.next'
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400532
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500533 def methodNext(self, previous):
Joe Gregorioa98733f2011-09-16 10:12:28 -0400534 """Retrieve the next page of results.
535
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400536 Takes a single argument, 'body', which is the results
537 from the last call, and returns the next set of items
538 in the collection.
539
Joe Gregorioa98733f2011-09-16 10:12:28 -0400540 Returns:
541 None if there are no more items in the collection.
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400542 """
Joe Gregorioaf276d22010-12-09 14:26:58 -0500543 if futureDesc['type'] != 'uri':
544 raise UnknownLinkType(futureDesc['type'])
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400545
546 try:
547 p = previous
Joe Gregorioaf276d22010-12-09 14:26:58 -0500548 for key in futureDesc['location']:
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400549 p = p[key]
550 url = p
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400551 except (KeyError, TypeError):
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400552 return None
553
Joe Gregorioa98733f2011-09-16 10:12:28 -0400554 url = _add_query_parameter(url, 'key', self._developerKey)
Joe Gregorio00cf1d92010-09-27 09:22:03 -0400555
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400556 headers = {}
557 headers, params, query, body = self._model.request(headers, {}, {}, None)
558
559 logging.info('URL being requested: %s' % url)
560 resp, content = self._http.request(url, method='GET', headers=headers)
561
Joe Gregorioabda96f2011-02-11 20:19:33 -0500562 return self._requestBuilder(self._http,
563 self._model.response,
564 url,
565 method='GET',
Joe Gregorioaf276d22010-12-09 14:26:58 -0500566 headers=headers,
Joe Gregorioaf276d22010-12-09 14:26:58 -0500567 methodId=methodId)
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400568
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500569 setattr(theclass, methodName, methodNext)
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400570
Joe Gregorio3c676f92011-07-25 10:38:14 -0400571 def createNextMethod(theclass, methodName, methodDesc, futureDesc):
572 methodName = _fix_method_name(methodName)
573 methodId = methodDesc['id'] + '.next'
574
575 def methodNext(self, previous_request, previous_response):
576 """Retrieves the next page of results.
577
578 Args:
579 previous_request: The request for the previous page.
580 previous_response: The response from the request for the previous page.
581
582 Returns:
583 A request object that you can call 'execute()' on to request the next
584 page. Returns None if there are no more items in the collection.
585 """
586 # Retrieve nextPageToken from previous_response
587 # Use as pageToken in previous_request to create new request.
588
589 if 'nextPageToken' not in previous_response:
590 return None
591
592 request = copy.copy(previous_request)
593
594 pageToken = previous_response['nextPageToken']
595 parsed = list(urlparse.urlparse(request.uri))
596 q = parse_qsl(parsed[4])
597
598 # Find and remove old 'pageToken' value from URI
599 newq = [(key, value) for (key, value) in q if key != 'pageToken']
600 newq.append(('pageToken', pageToken))
601 parsed[4] = urllib.urlencode(newq)
602 uri = urlparse.urlunparse(parsed)
603
604 request.uri = uri
605
606 logging.info('URL being requested: %s' % uri)
607
608 return request
609
610 setattr(theclass, methodName, methodNext)
611
612
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400613 # Add basic methods to Resource
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400614 if 'methods' in resourceDesc:
615 for methodName, methodDesc in resourceDesc['methods'].iteritems():
616 if futureDesc:
617 future = futureDesc['methods'].get(methodName, {})
618 else:
619 future = None
620 createMethod(Resource, methodName, methodDesc, future)
621
622 # Add in nested resources
623 if 'resources' in resourceDesc:
Joe Gregorioaf276d22010-12-09 14:26:58 -0500624
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500625 def createResourceMethod(theclass, methodName, methodDesc, futureDesc):
Joe Gregoriod92897c2011-07-07 11:44:56 -0400626 methodName = _fix_method_name(methodName)
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400627
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500628 def methodResource(self):
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400629 return createResource(self._http, self._baseUrl, self._model,
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500630 self._requestBuilder, self._developerKey,
Joe Gregorio3c676f92011-07-25 10:38:14 -0400631 methodDesc, futureDesc, schema)
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400632
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500633 setattr(methodResource, '__doc__', 'A collection resource.')
634 setattr(methodResource, '__is_resource__', True)
635 setattr(theclass, methodName, methodResource)
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400636
637 for methodName, methodDesc in resourceDesc['resources'].iteritems():
638 if futureDesc and 'resources' in futureDesc:
639 future = futureDesc['resources'].get(methodName, {})
640 else:
641 future = {}
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500642 createResourceMethod(Resource, methodName, methodDesc, future)
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400643
644 # Add <m>_next() methods to Resource
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500645 if futureDesc and 'methods' in futureDesc:
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400646 for methodName, methodDesc in futureDesc['methods'].iteritems():
647 if 'next' in methodDesc and methodName in resourceDesc['methods']:
Joe Gregorio3c676f92011-07-25 10:38:14 -0400648 createNextMethodFromFuture(Resource, methodName + '_next',
Joe Gregorioaf276d22010-12-09 14:26:58 -0500649 resourceDesc['methods'][methodName],
650 methodDesc['next'])
Joe Gregorio3c676f92011-07-25 10:38:14 -0400651 # Add _next() methods
652 # Look for response bodies in schema that contain nextPageToken, and methods
653 # that take a pageToken parameter.
654 if 'methods' in resourceDesc:
655 for methodName, methodDesc in resourceDesc['methods'].iteritems():
656 if 'response' in methodDesc:
657 responseSchema = methodDesc['response']
658 if '$ref' in responseSchema:
659 responseSchema = schema[responseSchema['$ref']]
Joe Gregorio555f33c2011-08-19 14:56:07 -0400660 hasNextPageToken = 'nextPageToken' in responseSchema.get('properties',
661 {})
Joe Gregorio3c676f92011-07-25 10:38:14 -0400662 hasPageToken = 'pageToken' in methodDesc.get('parameters', {})
663 if hasNextPageToken and hasPageToken:
664 createNextMethod(Resource, methodName + '_next',
665 resourceDesc['methods'][methodName],
666 methodName)
Joe Gregorio48d361f2010-08-18 13:19:21 -0400667
668 return Resource()