blob: a3d4beb5d2354aff9e53251db1e421a17d322dbc [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 Gregoriod0bd3882011-11-22 09:49:47 -050029import random
Joe Gregorio48d361f2010-08-18 13:19:21 -040030import re
Joe Gregorio48d361f2010-08-18 13:19:21 -040031import uritemplate
Joe Gregoriofe695fb2010-08-30 12:04:04 -040032import urllib
Joe Gregorio6d5e94f2010-08-25 23:49:30 -040033import urlparse
Joe Gregoriofdf7c802011-06-30 12:33:38 -040034import mimeparse
Joe Gregorio922b78c2011-05-26 21:36:34 -040035import mimetypes
36
ade@google.comc5eb46f2010-09-27 23:35:39 +010037try:
38 from urlparse import parse_qsl
39except ImportError:
40 from cgi import parse_qsl
Joe Gregorioaf276d22010-12-09 14:26:58 -050041
Joe Gregorio034e7002010-12-15 08:45:03 -050042from anyjson import simplejson
Joe Gregorio922b78c2011-05-26 21:36:34 -040043from email.mime.multipart import MIMEMultipart
44from email.mime.nonmultipart import MIMENonMultipart
Joe Gregorioc0e0fe92011-03-04 16:16:55 -050045from errors import HttpError
Joe Gregorio49396552011-03-08 10:39:00 -050046from errors import InvalidJsonError
Joe Gregoriofdf7c802011-06-30 12:33:38 -040047from errors import MediaUploadSizeError
48from errors import UnacceptableMimeTypeError
Joe Gregoriodae2f552011-11-21 08:16:56 -050049from errors import UnknownApiNameOrVersion
Joe Gregorio922b78c2011-05-26 21:36:34 -040050from errors import UnknownLinkType
51from http import HttpRequest
Joe Gregoriod0bd3882011-11-22 09:49:47 -050052from http import MediaUpload
53from http import MediaFileUpload
Joe Gregorio922b78c2011-05-26 21:36:34 -040054from model import JsonModel
Joe Gregorio48d361f2010-08-18 13:19:21 -040055
Joe Gregoriobc2ff9b2010-11-08 09:20:48 -050056URITEMPLATE = re.compile('{[^}]*}')
57VARNAME = re.compile('[a-zA-Z0-9_-]+')
Joe Gregorio6a63a762011-05-02 22:36:05 -040058DISCOVERY_URI = ('https://www.googleapis.com/discovery/v1/apis/'
59 '{api}/{apiVersion}/rest')
Joe Gregorioc3fae8a2011-02-18 14:19:50 -050060DEFAULT_METHOD_DOC = 'A description of how to use this function'
Joe Gregorioca876e42011-02-22 19:39:42 -050061
62# Query parameters that work, but don't appear in discovery
Joe Gregorio06d852b2011-03-25 15:03:10 -040063STACK_QUERY_PARAMETERS = ['trace', 'fields', 'pp', 'prettyPrint', 'userIp',
Joe Gregorio3eecaa92011-05-17 13:40:12 -040064 'userip', 'strict']
Joe Gregorio48d361f2010-08-18 13:19:21 -040065
Joe Gregorio562b7312011-09-15 09:06:38 -040066RESERVED_WORDS = ['and', 'assert', 'break', 'class', 'continue', 'def', 'del',
Joe Gregoriod92897c2011-07-07 11:44:56 -040067 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from',
68 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or',
69 'pass', 'print', 'raise', 'return', 'try', 'while' ]
70
Joe Gregorio562b7312011-09-15 09:06:38 -040071
Joe Gregoriod92897c2011-07-07 11:44:56 -040072def _fix_method_name(name):
73 if name in RESERVED_WORDS:
74 return name + '_'
75 else:
76 return name
Joe Gregorio48d361f2010-08-18 13:19:21 -040077
Joe Gregorioa98733f2011-09-16 10:12:28 -040078
Joe Gregorio922b78c2011-05-26 21:36:34 -040079def _write_headers(self):
80 # Utility no-op method for multipart media handling
81 pass
82
83
Joe Gregorioa98733f2011-09-16 10:12:28 -040084def _add_query_parameter(url, name, value):
85 """Adds a query parameter to a url
86
87 Args:
88 url: string, url to add the query parameter to.
89 name: string, query parameter name.
90 value: string, query parameter value.
91
92 Returns:
93 Updated query parameter. Does not update the url if value is None.
94 """
95 if value is None:
96 return url
97 else:
98 parsed = list(urlparse.urlparse(url))
99 q = parse_qsl(parsed[4])
100 q.append((name, value))
101 parsed[4] = urllib.urlencode(q)
102 return urlparse.urlunparse(parsed)
103
104
Joe Gregorio48d361f2010-08-18 13:19:21 -0400105def key2param(key):
Joe Gregorio7c22ab22011-02-16 15:32:39 -0500106 """Converts key names into parameter names.
107
108 For example, converting "max-results" -> "max_results"
Joe Gregorio48d361f2010-08-18 13:19:21 -0400109 """
110 result = []
111 key = list(key)
112 if not key[0].isalpha():
113 result.append('x')
114 for c in key:
115 if c.isalnum():
116 result.append(c)
117 else:
118 result.append('_')
119
120 return ''.join(result)
121
122
Joe Gregorioaf276d22010-12-09 14:26:58 -0500123def build(serviceName, version,
Joe Gregorio3fada332011-01-07 17:07:45 -0500124 http=None,
125 discoveryServiceUrl=DISCOVERY_URI,
126 developerKey=None,
Joe Gregoriod433b2a2011-02-22 10:51:51 -0500127 model=None,
Joe Gregorio3fada332011-01-07 17:07:45 -0500128 requestBuilder=HttpRequest):
Joe Gregorioabda96f2011-02-11 20:19:33 -0500129 """Construct a Resource for interacting with an API.
130
131 Construct a Resource object for interacting with
132 an API. The serviceName and version are the
133 names from the Discovery service.
134
135 Args:
136 serviceName: string, name of the service
137 version: string, the version of the service
138 discoveryServiceUrl: string, a URI Template that points to
139 the location of the discovery service. It should have two
140 parameters {api} and {apiVersion} that when filled in
141 produce an absolute URI to the discovery document for
142 that service.
Joe Gregoriodeeb0202011-02-15 14:49:57 -0500143 developerKey: string, key obtained
144 from https://code.google.com/apis/console
Joe Gregorioabda96f2011-02-11 20:19:33 -0500145 model: apiclient.Model, converts to and from the wire format
Joe Gregoriodeeb0202011-02-15 14:49:57 -0500146 requestBuilder: apiclient.http.HttpRequest, encapsulator for
147 an HTTP request
Joe Gregorioabda96f2011-02-11 20:19:33 -0500148
149 Returns:
150 A Resource object with methods for interacting with
151 the service.
152 """
Joe Gregorio48d361f2010-08-18 13:19:21 -0400153 params = {
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400154 'api': serviceName,
Joe Gregorio48d361f2010-08-18 13:19:21 -0400155 'apiVersion': version
156 }
ade@google.com850cf552010-08-20 23:24:56 +0100157
Joe Gregorioc204b642010-09-21 12:01:23 -0400158 if http is None:
159 http = httplib2.Http()
Joe Gregorioa98733f2011-09-16 10:12:28 -0400160
ade@google.com850cf552010-08-20 23:24:56 +0100161 requested_url = uritemplate.expand(discoveryServiceUrl, params)
Joe Gregorio583d9e42011-09-16 15:54:15 -0400162
Joe Gregorio66f57522011-11-30 11:00:00 -0500163 # REMOTE_ADDR is defined by the CGI spec [RFC3875] as the environment
164 # variable that contains the network address of the client sending the
165 # request. If it exists then add that to the request for the discovery
166 # document to avoid exceeding the quota on discovery requests.
Joe Gregorio583d9e42011-09-16 15:54:15 -0400167 if 'REMOTE_ADDR' in os.environ:
168 requested_url = _add_query_parameter(requested_url, 'userIp',
169 os.environ['REMOTE_ADDR'])
ade@google.com850cf552010-08-20 23:24:56 +0100170 logging.info('URL being requested: %s' % requested_url)
Joe Gregorioa98733f2011-09-16 10:12:28 -0400171
ade@google.com850cf552010-08-20 23:24:56 +0100172 resp, content = http.request(requested_url)
Joe Gregorioa98733f2011-09-16 10:12:28 -0400173
Joe Gregorio8b4df3f2011-11-18 15:44:48 -0500174 if resp.status == 404:
Joe Gregoriodae2f552011-11-21 08:16:56 -0500175 raise UnknownApiNameOrVersion("name: %s version: %s" % (serviceName,
Joe Gregorio8b4df3f2011-11-18 15:44:48 -0500176 version))
Joe Gregorioa98733f2011-09-16 10:12:28 -0400177 if resp.status >= 400:
Joe Gregorio49396552011-03-08 10:39:00 -0500178 raise HttpError(resp, content, requested_url)
Joe Gregorioa98733f2011-09-16 10:12:28 -0400179
Joe Gregorioc0e0fe92011-03-04 16:16:55 -0500180 try:
181 service = simplejson.loads(content)
182 except ValueError, e:
Joe Gregorio205e73a2011-03-12 09:55:31 -0500183 logging.error('Failed to parse as JSON: ' + content)
Joe Gregorio49396552011-03-08 10:39:00 -0500184 raise InvalidJsonError()
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400185
Joe Gregorioa98733f2011-09-16 10:12:28 -0400186 filename = os.path.join(os.path.dirname(__file__), 'contrib',
Joe Gregorio7c22ab22011-02-16 15:32:39 -0500187 serviceName, 'future.json')
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400188 try:
Joe Gregorioa98733f2011-09-16 10:12:28 -0400189 f = file(filename, 'r')
Joe Gregorio292b9b82011-01-12 11:36:11 -0500190 future = f.read()
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400191 f.close()
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400192 except IOError:
Joe Gregorio292b9b82011-01-12 11:36:11 -0500193 future = None
194
195 return build_from_document(content, discoveryServiceUrl, future,
196 http, developerKey, model, requestBuilder)
197
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500198
Joe Gregorio292b9b82011-01-12 11:36:11 -0500199def build_from_document(
200 service,
201 base,
202 future=None,
203 http=None,
204 developerKey=None,
Joe Gregoriod433b2a2011-02-22 10:51:51 -0500205 model=None,
Joe Gregorio292b9b82011-01-12 11:36:11 -0500206 requestBuilder=HttpRequest):
Joe Gregorioabda96f2011-02-11 20:19:33 -0500207 """Create a Resource for interacting with an API.
208
209 Same as `build()`, but constructs the Resource object
210 from a discovery document that is it given, as opposed to
211 retrieving one over HTTP.
212
Joe Gregorio292b9b82011-01-12 11:36:11 -0500213 Args:
214 service: string, discovery document
215 base: string, base URI for all HTTP requests, usually the discovery URI
216 future: string, discovery document with future capabilities
217 auth_discovery: dict, information about the authentication the API supports
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500218 http: httplib2.Http, An instance of httplib2.Http or something that acts
219 like it that HTTP requests will be made through.
Joe Gregorio292b9b82011-01-12 11:36:11 -0500220 developerKey: string, Key for controlling API usage, generated
221 from the API Console.
222 model: Model class instance that serializes and
223 de-serializes requests and responses.
224 requestBuilder: Takes an http request and packages it up to be executed.
Joe Gregorioabda96f2011-02-11 20:19:33 -0500225
226 Returns:
227 A Resource object with methods for interacting with
228 the service.
Joe Gregorio292b9b82011-01-12 11:36:11 -0500229 """
230
231 service = simplejson.loads(service)
Joe Gregorio6a63a762011-05-02 22:36:05 -0400232 base = urlparse.urljoin(base, service['basePath'])
Joe Gregorio292b9b82011-01-12 11:36:11 -0500233 if future:
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500234 future = simplejson.loads(future)
235 auth_discovery = future.get('auth', {})
Joe Gregorio292b9b82011-01-12 11:36:11 -0500236 else:
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400237 future = {}
238 auth_discovery = {}
Joe Gregorio3c676f92011-07-25 10:38:14 -0400239 schema = service.get('schemas', {})
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400240
Joe Gregoriod433b2a2011-02-22 10:51:51 -0500241 if model is None:
Joe Gregoriof863f7a2011-02-24 03:24:44 -0500242 features = service.get('features', [])
Joe Gregorio266c6442011-02-23 16:08:54 -0500243 model = JsonModel('dataWrapper' in features)
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500244 resource = createResource(http, base, model, requestBuilder, developerKey,
Joe Gregorio3c676f92011-07-25 10:38:14 -0400245 service, future, schema)
Joe Gregorio48d361f2010-08-18 13:19:21 -0400246
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500247 def auth_method():
248 """Discovery information about the authentication the API uses."""
249 return auth_discovery
Joe Gregorio48d361f2010-08-18 13:19:21 -0400250
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500251 setattr(resource, 'auth_discovery', auth_method)
Joe Gregorioa2f56e72010-09-09 15:15:56 -0400252
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500253 return resource
Joe Gregorio48d361f2010-08-18 13:19:21 -0400254
255
Joe Gregorio61d7e962011-02-22 22:52:07 -0500256def _cast(value, schema_type):
Joe Gregoriobee86832011-02-22 10:00:19 -0500257 """Convert value to a string based on JSON Schema type.
258
259 See http://tools.ietf.org/html/draft-zyp-json-schema-03 for more details on
260 JSON Schema.
261
262 Args:
263 value: any, the value to convert
264 schema_type: string, the type that value should be interpreted as
265
266 Returns:
267 A string representation of 'value' based on the schema_type.
268 """
269 if schema_type == 'string':
Joe Gregoriof863f7a2011-02-24 03:24:44 -0500270 if type(value) == type('') or type(value) == type(u''):
271 return value
272 else:
273 return str(value)
Joe Gregoriobee86832011-02-22 10:00:19 -0500274 elif schema_type == 'integer':
275 return str(int(value))
276 elif schema_type == 'number':
277 return str(float(value))
278 elif schema_type == 'boolean':
279 return str(bool(value)).lower()
280 else:
Joe Gregoriof863f7a2011-02-24 03:24:44 -0500281 if type(value) == type('') or type(value) == type(u''):
282 return value
283 else:
284 return str(value)
Joe Gregoriobee86832011-02-22 10:00:19 -0500285
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400286MULTIPLIERS = {
Joe Gregorio562b7312011-09-15 09:06:38 -0400287 "KB": 2 ** 10,
288 "MB": 2 ** 20,
289 "GB": 2 ** 30,
290 "TB": 2 ** 40,
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400291 }
292
Joe Gregorioa98733f2011-09-16 10:12:28 -0400293
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400294def _media_size_to_long(maxSize):
295 """Convert a string media size, such as 10GB or 3TB into an integer."""
Joe Gregorio84d3c1f2011-07-25 10:39:45 -0400296 if len(maxSize) < 2:
297 return 0
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400298 units = maxSize[-2:].upper()
299 multiplier = MULTIPLIERS.get(units, 0)
300 if multiplier:
Joe Gregorio562b7312011-09-15 09:06:38 -0400301 return int(maxSize[:-2]) * multiplier
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400302 else:
303 return int(maxSize)
304
Joe Gregoriobee86832011-02-22 10:00:19 -0500305
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500306def createResource(http, baseUrl, model, requestBuilder,
Joe Gregorio3c676f92011-07-25 10:38:14 -0400307 developerKey, resourceDesc, futureDesc, schema):
Joe Gregorio48d361f2010-08-18 13:19:21 -0400308
309 class Resource(object):
310 """A class for interacting with a resource."""
311
312 def __init__(self):
313 self._http = http
314 self._baseUrl = baseUrl
315 self._model = model
Joe Gregorio00cf1d92010-09-27 09:22:03 -0400316 self._developerKey = developerKey
Joe Gregorioaf276d22010-12-09 14:26:58 -0500317 self._requestBuilder = requestBuilder
Joe Gregorio48d361f2010-08-18 13:19:21 -0400318
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400319 def createMethod(theclass, methodName, methodDesc, futureDesc):
Joe Gregoriod92897c2011-07-07 11:44:56 -0400320 methodName = _fix_method_name(methodName)
Joe Gregorio6a63a762011-05-02 22:36:05 -0400321 pathUrl = methodDesc['path']
Joe Gregorio48d361f2010-08-18 13:19:21 -0400322 httpMethod = methodDesc['httpMethod']
Joe Gregorio6a63a762011-05-02 22:36:05 -0400323 methodId = methodDesc['id']
Joe Gregorio21f11672010-08-18 17:23:17 -0400324
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400325 mediaPathUrl = None
326 accept = []
327 maxSize = 0
328 if 'mediaUpload' in methodDesc:
329 mediaUpload = methodDesc['mediaUpload']
330 mediaPathUrl = mediaUpload['protocols']['simple']['path']
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500331 mediaResumablePathUrl = mediaUpload['protocols']['resumable']['path']
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400332 accept = mediaUpload['accept']
Joe Gregorio84d3c1f2011-07-25 10:39:45 -0400333 maxSize = _media_size_to_long(mediaUpload.get('maxSize', ''))
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400334
Joe Gregorioca876e42011-02-22 19:39:42 -0500335 if 'parameters' not in methodDesc:
336 methodDesc['parameters'] = {}
337 for name in STACK_QUERY_PARAMETERS:
338 methodDesc['parameters'][name] = {
339 'type': 'string',
Joe Gregorio6a63a762011-05-02 22:36:05 -0400340 'location': 'query'
Joe Gregorioca876e42011-02-22 19:39:42 -0500341 }
342
Joe Gregoriof4153422011-03-18 22:45:18 -0400343 if httpMethod in ['PUT', 'POST', 'PATCH']:
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500344 methodDesc['parameters']['body'] = {
345 'description': 'The request body.',
Joe Gregorioc2a73932011-02-22 10:17:06 -0500346 'type': 'object',
Joe Gregorio1ae3e742011-02-25 15:17:14 -0500347 'required': True,
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500348 }
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400349 if 'mediaUpload' in methodDesc:
350 methodDesc['parameters']['media_body'] = {
351 'description': 'The filename of the media request body.',
352 'type': 'string',
353 'required': False,
354 }
355 methodDesc['parameters']['body']['required'] = False
ade@google.com850cf552010-08-20 23:24:56 +0100356
Joe Gregorioca876e42011-02-22 19:39:42 -0500357 argmap = {} # Map from method parameter name to query parameter name
ade@google.com850cf552010-08-20 23:24:56 +0100358 required_params = [] # Required parameters
Joe Gregorio61d7e962011-02-22 22:52:07 -0500359 repeated_params = [] # Repeated parameters
ade@google.com850cf552010-08-20 23:24:56 +0100360 pattern_params = {} # Parameters that must match a regex
361 query_params = [] # Parameters that will be used in the query string
362 path_params = {} # Parameters that will be used in the base URL
Joe Gregoriobee86832011-02-22 10:00:19 -0500363 param_type = {} # The type of the parameter
Joe Gregorioca876e42011-02-22 19:39:42 -0500364 enum_params = {} # Allowable enumeration values for each parameter
365
366
Joe Gregorio4292c6e2010-09-09 14:32:43 -0400367 if 'parameters' in methodDesc:
368 for arg, desc in methodDesc['parameters'].iteritems():
369 param = key2param(arg)
370 argmap[param] = arg
Joe Gregorio21f11672010-08-18 17:23:17 -0400371
Joe Gregorio4292c6e2010-09-09 14:32:43 -0400372 if desc.get('pattern', ''):
373 pattern_params[param] = desc['pattern']
Joe Gregoriobee86832011-02-22 10:00:19 -0500374 if desc.get('enum', ''):
375 enum_params[param] = desc['enum']
Joe Gregorio4292c6e2010-09-09 14:32:43 -0400376 if desc.get('required', False):
377 required_params.append(param)
Joe Gregorio61d7e962011-02-22 22:52:07 -0500378 if desc.get('repeated', False):
379 repeated_params.append(param)
Joe Gregorio6a63a762011-05-02 22:36:05 -0400380 if desc.get('location') == 'query':
Joe Gregorio4292c6e2010-09-09 14:32:43 -0400381 query_params.append(param)
Joe Gregorio6a63a762011-05-02 22:36:05 -0400382 if desc.get('location') == 'path':
Joe Gregorio4292c6e2010-09-09 14:32:43 -0400383 path_params[param] = param
Joe Gregoriobee86832011-02-22 10:00:19 -0500384 param_type[param] = desc.get('type', 'string')
Joe Gregorio48d361f2010-08-18 13:19:21 -0400385
Joe Gregoriobc2ff9b2010-11-08 09:20:48 -0500386 for match in URITEMPLATE.finditer(pathUrl):
387 for namematch in VARNAME.finditer(match.group(0)):
388 name = key2param(namematch.group(0))
389 path_params[name] = name
390 if name in query_params:
391 query_params.remove(name)
392
Joe Gregorio48d361f2010-08-18 13:19:21 -0400393 def method(self, **kwargs):
394 for name in kwargs.iterkeys():
Joe Gregorioca876e42011-02-22 19:39:42 -0500395 if name not in argmap:
Joe Gregorio48d361f2010-08-18 13:19:21 -0400396 raise TypeError('Got an unexpected keyword argument "%s"' % name)
Joe Gregorio21f11672010-08-18 17:23:17 -0400397
ade@google.com850cf552010-08-20 23:24:56 +0100398 for name in required_params:
Joe Gregoriofbf9d0d2010-08-18 16:50:47 -0400399 if name not in kwargs:
400 raise TypeError('Missing required parameter "%s"' % name)
Joe Gregorio21f11672010-08-18 17:23:17 -0400401
ade@google.com850cf552010-08-20 23:24:56 +0100402 for name, regex in pattern_params.iteritems():
Joe Gregorio21f11672010-08-18 17:23:17 -0400403 if name in kwargs:
Joe Gregorio6804c7a2011-11-18 14:30:32 -0500404 if isinstance(kwargs[name], basestring):
405 pvalues = [kwargs[name]]
406 else:
407 pvalues = kwargs[name]
408 for pvalue in pvalues:
409 if re.match(regex, pvalue) is None:
410 raise TypeError(
411 'Parameter "%s" value "%s" does not match the pattern "%s"' %
412 (name, pvalue, regex))
Joe Gregorio21f11672010-08-18 17:23:17 -0400413
Joe Gregoriobee86832011-02-22 10:00:19 -0500414 for name, enums in enum_params.iteritems():
415 if name in kwargs:
416 if kwargs[name] not in enums:
417 raise TypeError(
Joe Gregorioca876e42011-02-22 19:39:42 -0500418 'Parameter "%s" value "%s" is not an allowed value in "%s"' %
Joe Gregoriobee86832011-02-22 10:00:19 -0500419 (name, kwargs[name], str(enums)))
420
ade@google.com850cf552010-08-20 23:24:56 +0100421 actual_query_params = {}
422 actual_path_params = {}
Joe Gregorio21f11672010-08-18 17:23:17 -0400423 for key, value in kwargs.iteritems():
Joe Gregorio61d7e962011-02-22 22:52:07 -0500424 to_type = param_type.get(key, 'string')
425 # For repeated parameters we cast each member of the list.
426 if key in repeated_params and type(value) == type([]):
427 cast_value = [_cast(x, to_type) for x in value]
428 else:
429 cast_value = _cast(value, to_type)
ade@google.com850cf552010-08-20 23:24:56 +0100430 if key in query_params:
Joe Gregorio61d7e962011-02-22 22:52:07 -0500431 actual_query_params[argmap[key]] = cast_value
ade@google.com850cf552010-08-20 23:24:56 +0100432 if key in path_params:
Joe Gregorio61d7e962011-02-22 22:52:07 -0500433 actual_path_params[argmap[key]] = cast_value
ade@google.com850cf552010-08-20 23:24:56 +0100434 body_value = kwargs.get('body', None)
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400435 media_filename = kwargs.get('media_body', None)
Joe Gregorio21f11672010-08-18 17:23:17 -0400436
Joe Gregorio00cf1d92010-09-27 09:22:03 -0400437 if self._developerKey:
438 actual_query_params['key'] = self._developerKey
439
Joe Gregorio48d361f2010-08-18 13:19:21 -0400440 headers = {}
Joe Gregorio3bbbf662010-08-30 16:41:53 -0400441 headers, params, query, body = self._model.request(headers,
442 actual_path_params, actual_query_params, body_value)
Joe Gregorio48d361f2010-08-18 13:19:21 -0400443
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400444 expanded_url = uritemplate.expand(pathUrl, params)
Joe Gregorio922b78c2011-05-26 21:36:34 -0400445 url = urlparse.urljoin(self._baseUrl, expanded_url + query)
446
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500447 resumable = None
448 multipart_boundary = ''
449
Joe Gregorio922b78c2011-05-26 21:36:34 -0400450 if media_filename:
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500451 # Convert a simple filename into a MediaUpload object.
452 if isinstance(media_filename, basestring):
453 (media_mime_type, encoding) = mimetypes.guess_type(media_filename)
454 if media_mime_type is None:
455 raise UnknownFileType(media_filename)
456 if not mimeparse.best_match([media_mime_type], ','.join(accept)):
457 raise UnacceptableMimeTypeError(media_mime_type)
458 media_upload = MediaFileUpload(media_filename, media_mime_type)
459 elif isinstance(media_filename, MediaUpload):
460 media_upload = media_filename
461 else:
Joe Gregorio66f57522011-11-30 11:00:00 -0500462 raise TypeError('media_filename must be str or MediaUpload.')
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500463
464 if media_upload.resumable():
465 resumable = media_upload
Joe Gregorio922b78c2011-05-26 21:36:34 -0400466
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400467 # Check the maxSize
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500468 if maxSize > 0 and media_upload.size() > maxSize:
469 raise MediaUploadSizeError("Media larger than: %s" % maxSize)
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400470
471 # Use the media path uri for media uploads
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500472 if media_upload.resumable():
473 expanded_url = uritemplate.expand(mediaResumablePathUrl, params)
474 else:
475 expanded_url = uritemplate.expand(mediaPathUrl, params)
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400476 url = urlparse.urljoin(self._baseUrl, expanded_url + query)
Joe Gregorio922b78c2011-05-26 21:36:34 -0400477
478 if body is None:
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500479 # This is a simple media upload
480 headers['content-type'] = media_upload.mimetype()
481 expanded_url = uritemplate.expand(mediaResumablePathUrl, params)
482 if not media_upload.resumable():
483 body = media_upload.getbytes(0, media_upload.size())
Joe Gregorio922b78c2011-05-26 21:36:34 -0400484 else:
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500485 # This is a multipart/related upload.
Joe Gregorio922b78c2011-05-26 21:36:34 -0400486 msgRoot = MIMEMultipart('related')
487 # msgRoot should not write out it's own headers
488 setattr(msgRoot, '_write_headers', lambda self: None)
489
490 # attach the body as one part
491 msg = MIMENonMultipart(*headers['content-type'].split('/'))
492 msg.set_payload(body)
493 msgRoot.attach(msg)
494
495 # attach the media as the second part
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500496 msg = MIMENonMultipart(*media_upload.mimetype().split('/'))
Joe Gregorio922b78c2011-05-26 21:36:34 -0400497 msg['Content-Transfer-Encoding'] = 'binary'
498
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500499 if media_upload.resumable():
500 # This is a multipart resumable upload, where a multipart payload
501 # looks like this:
502 #
503 # --===============1678050750164843052==
504 # Content-Type: application/json
505 # MIME-Version: 1.0
506 #
507 # {'foo': 'bar'}
508 # --===============1678050750164843052==
509 # Content-Type: image/png
510 # MIME-Version: 1.0
511 # Content-Transfer-Encoding: binary
512 #
513 # <BINARY STUFF>
514 # --===============1678050750164843052==--
515 #
516 # In the case of resumable multipart media uploads, the <BINARY
517 # STUFF> is large and will be spread across multiple PUTs. What we
518 # do here is compose the multipart message with a random payload in
519 # place of <BINARY STUFF> and then split the resulting content into
520 # two pieces, text before <BINARY STUFF> and text after <BINARY
521 # STUFF>. The text after <BINARY STUFF> is the multipart boundary.
522 # In apiclient.http the HttpRequest will send the text before
523 # <BINARY STUFF>, then send the actual binary media in chunks, and
524 # then will send the multipart delimeter.
Joe Gregorio922b78c2011-05-26 21:36:34 -0400525
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500526 payload = hex(random.getrandbits(300))
527 msg.set_payload(payload)
528 msgRoot.attach(msg)
529 body = msgRoot.as_string()
530 body, _ = body.split(payload)
531 resumable = media_upload
532 else:
533 payload = media_upload.getbytes(0, media_upload.size())
534 msg.set_payload(payload)
535 msgRoot.attach(msg)
536 body = msgRoot.as_string()
Joe Gregorio922b78c2011-05-26 21:36:34 -0400537
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500538 multipart_boundary = msgRoot.get_boundary()
Joe Gregorio922b78c2011-05-26 21:36:34 -0400539 headers['content-type'] = ('multipart/related; '
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500540 'boundary="%s"') % multipart_boundary
Joe Gregoriofbf9d0d2010-08-18 16:50:47 -0400541
ade@google.com850cf552010-08-20 23:24:56 +0100542 logging.info('URL being requested: %s' % url)
Joe Gregorioabda96f2011-02-11 20:19:33 -0500543 return self._requestBuilder(self._http,
544 self._model.response,
545 url,
546 method=httpMethod,
547 body=body,
Joe Gregorioaf276d22010-12-09 14:26:58 -0500548 headers=headers,
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500549 methodId=methodId,
550 resumable=resumable)
Joe Gregorio48d361f2010-08-18 13:19:21 -0400551
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500552 docs = [methodDesc.get('description', DEFAULT_METHOD_DOC), '\n\n']
553 if len(argmap) > 0:
Joe Gregorio61d7e962011-02-22 22:52:07 -0500554 docs.append('Args:\n')
Joe Gregorio48d361f2010-08-18 13:19:21 -0400555 for arg in argmap.iterkeys():
Joe Gregorioca876e42011-02-22 19:39:42 -0500556 if arg in STACK_QUERY_PARAMETERS:
557 continue
Joe Gregorio61d7e962011-02-22 22:52:07 -0500558 repeated = ''
559 if arg in repeated_params:
560 repeated = ' (repeated)'
561 required = ''
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400562 if arg in required_params:
Joe Gregorio61d7e962011-02-22 22:52:07 -0500563 required = ' (required)'
Joe Gregorioc2a73932011-02-22 10:17:06 -0500564 paramdesc = methodDesc['parameters'][argmap[arg]]
565 paramdoc = paramdesc.get('description', 'A parameter')
566 paramtype = paramdesc.get('type', 'string')
Joe Gregorio61d7e962011-02-22 22:52:07 -0500567 docs.append(' %s: %s, %s%s%s\n' % (arg, paramtype, paramdoc, required,
568 repeated))
Joe Gregorioc2a73932011-02-22 10:17:06 -0500569 enum = paramdesc.get('enum', [])
570 enumDesc = paramdesc.get('enumDescriptions', [])
571 if enum and enumDesc:
572 docs.append(' Allowed values\n')
573 for (name, desc) in zip(enum, enumDesc):
574 docs.append(' %s - %s\n' % (name, desc))
Joe Gregorio48d361f2010-08-18 13:19:21 -0400575
576 setattr(method, '__doc__', ''.join(docs))
577 setattr(theclass, methodName, method)
578
Joe Gregorio3c676f92011-07-25 10:38:14 -0400579 def createNextMethodFromFuture(theclass, methodName, methodDesc, futureDesc):
Joe Gregorioa98733f2011-09-16 10:12:28 -0400580 """ This is a legacy method, as only Buzz and Moderator use the future.json
581 functionality for generating _next methods. It will be kept around as long
582 as those API versions are around, but no new APIs should depend upon it.
583 """
Joe Gregoriod92897c2011-07-07 11:44:56 -0400584 methodName = _fix_method_name(methodName)
Joe Gregorio6a63a762011-05-02 22:36:05 -0400585 methodId = methodDesc['id'] + '.next'
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400586
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500587 def methodNext(self, previous):
Joe Gregorioa98733f2011-09-16 10:12:28 -0400588 """Retrieve the next page of results.
589
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400590 Takes a single argument, 'body', which is the results
591 from the last call, and returns the next set of items
592 in the collection.
593
Joe Gregorioa98733f2011-09-16 10:12:28 -0400594 Returns:
595 None if there are no more items in the collection.
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400596 """
Joe Gregorioaf276d22010-12-09 14:26:58 -0500597 if futureDesc['type'] != 'uri':
598 raise UnknownLinkType(futureDesc['type'])
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400599
600 try:
601 p = previous
Joe Gregorioaf276d22010-12-09 14:26:58 -0500602 for key in futureDesc['location']:
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400603 p = p[key]
604 url = p
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400605 except (KeyError, TypeError):
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400606 return None
607
Joe Gregorioa98733f2011-09-16 10:12:28 -0400608 url = _add_query_parameter(url, 'key', self._developerKey)
Joe Gregorio00cf1d92010-09-27 09:22:03 -0400609
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400610 headers = {}
611 headers, params, query, body = self._model.request(headers, {}, {}, None)
612
613 logging.info('URL being requested: %s' % url)
614 resp, content = self._http.request(url, method='GET', headers=headers)
615
Joe Gregorioabda96f2011-02-11 20:19:33 -0500616 return self._requestBuilder(self._http,
617 self._model.response,
618 url,
619 method='GET',
Joe Gregorioaf276d22010-12-09 14:26:58 -0500620 headers=headers,
Joe Gregorioaf276d22010-12-09 14:26:58 -0500621 methodId=methodId)
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400622
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500623 setattr(theclass, methodName, methodNext)
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400624
Joe Gregorio3c676f92011-07-25 10:38:14 -0400625 def createNextMethod(theclass, methodName, methodDesc, futureDesc):
626 methodName = _fix_method_name(methodName)
627 methodId = methodDesc['id'] + '.next'
628
629 def methodNext(self, previous_request, previous_response):
630 """Retrieves the next page of results.
631
632 Args:
633 previous_request: The request for the previous page.
634 previous_response: The response from the request for the previous page.
635
636 Returns:
637 A request object that you can call 'execute()' on to request the next
638 page. Returns None if there are no more items in the collection.
639 """
640 # Retrieve nextPageToken from previous_response
641 # Use as pageToken in previous_request to create new request.
642
643 if 'nextPageToken' not in previous_response:
644 return None
645
646 request = copy.copy(previous_request)
647
648 pageToken = previous_response['nextPageToken']
649 parsed = list(urlparse.urlparse(request.uri))
650 q = parse_qsl(parsed[4])
651
652 # Find and remove old 'pageToken' value from URI
653 newq = [(key, value) for (key, value) in q if key != 'pageToken']
654 newq.append(('pageToken', pageToken))
655 parsed[4] = urllib.urlencode(newq)
656 uri = urlparse.urlunparse(parsed)
657
658 request.uri = uri
659
660 logging.info('URL being requested: %s' % uri)
661
662 return request
663
664 setattr(theclass, methodName, methodNext)
665
666
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400667 # Add basic methods to Resource
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400668 if 'methods' in resourceDesc:
669 for methodName, methodDesc in resourceDesc['methods'].iteritems():
670 if futureDesc:
671 future = futureDesc['methods'].get(methodName, {})
672 else:
673 future = None
674 createMethod(Resource, methodName, methodDesc, future)
675
676 # Add in nested resources
677 if 'resources' in resourceDesc:
Joe Gregorioaf276d22010-12-09 14:26:58 -0500678
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500679 def createResourceMethod(theclass, methodName, methodDesc, futureDesc):
Joe Gregoriod92897c2011-07-07 11:44:56 -0400680 methodName = _fix_method_name(methodName)
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400681
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500682 def methodResource(self):
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400683 return createResource(self._http, self._baseUrl, self._model,
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500684 self._requestBuilder, self._developerKey,
Joe Gregorio3c676f92011-07-25 10:38:14 -0400685 methodDesc, futureDesc, schema)
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400686
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500687 setattr(methodResource, '__doc__', 'A collection resource.')
688 setattr(methodResource, '__is_resource__', True)
689 setattr(theclass, methodName, methodResource)
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400690
691 for methodName, methodDesc in resourceDesc['resources'].iteritems():
692 if futureDesc and 'resources' in futureDesc:
693 future = futureDesc['resources'].get(methodName, {})
694 else:
695 future = {}
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500696 createResourceMethod(Resource, methodName, methodDesc, future)
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400697
698 # Add <m>_next() methods to Resource
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500699 if futureDesc and 'methods' in futureDesc:
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400700 for methodName, methodDesc in futureDesc['methods'].iteritems():
701 if 'next' in methodDesc and methodName in resourceDesc['methods']:
Joe Gregorio3c676f92011-07-25 10:38:14 -0400702 createNextMethodFromFuture(Resource, methodName + '_next',
Joe Gregorioaf276d22010-12-09 14:26:58 -0500703 resourceDesc['methods'][methodName],
704 methodDesc['next'])
Joe Gregorio3c676f92011-07-25 10:38:14 -0400705 # Add _next() methods
706 # Look for response bodies in schema that contain nextPageToken, and methods
707 # that take a pageToken parameter.
708 if 'methods' in resourceDesc:
709 for methodName, methodDesc in resourceDesc['methods'].iteritems():
710 if 'response' in methodDesc:
711 responseSchema = methodDesc['response']
712 if '$ref' in responseSchema:
713 responseSchema = schema[responseSchema['$ref']]
Joe Gregorio555f33c2011-08-19 14:56:07 -0400714 hasNextPageToken = 'nextPageToken' in responseSchema.get('properties',
715 {})
Joe Gregorio3c676f92011-07-25 10:38:14 -0400716 hasPageToken = 'pageToken' in methodDesc.get('parameters', {})
717 if hasNextPageToken and hasPageToken:
718 createNextMethod(Resource, methodName + '_next',
719 resourceDesc['methods'][methodName],
720 methodName)
Joe Gregorio48d361f2010-08-18 13:19:21 -0400721
722 return Resource()