blob: ca26025351bfed8653b86fb0cc84e4521f937046 [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 Gregorioe08a1662011-12-07 09:48:22 -050055from model import RawModel
Joe Gregorio48d361f2010-08-18 13:19:21 -040056
Joe Gregoriobc2ff9b2010-11-08 09:20:48 -050057URITEMPLATE = re.compile('{[^}]*}')
58VARNAME = re.compile('[a-zA-Z0-9_-]+')
Joe Gregorio6a63a762011-05-02 22:36:05 -040059DISCOVERY_URI = ('https://www.googleapis.com/discovery/v1/apis/'
60 '{api}/{apiVersion}/rest')
Joe Gregorioc3fae8a2011-02-18 14:19:50 -050061DEFAULT_METHOD_DOC = 'A description of how to use this function'
Joe Gregorioca876e42011-02-22 19:39:42 -050062
63# Query parameters that work, but don't appear in discovery
Joe Gregorio06d852b2011-03-25 15:03:10 -040064STACK_QUERY_PARAMETERS = ['trace', 'fields', 'pp', 'prettyPrint', 'userIp',
Joe Gregorio3eecaa92011-05-17 13:40:12 -040065 'userip', 'strict']
Joe Gregorio48d361f2010-08-18 13:19:21 -040066
Joe Gregorio562b7312011-09-15 09:06:38 -040067RESERVED_WORDS = ['and', 'assert', 'break', 'class', 'continue', 'def', 'del',
Joe Gregoriod92897c2011-07-07 11:44:56 -040068 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from',
69 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or',
70 'pass', 'print', 'raise', 'return', 'try', 'while' ]
71
Joe Gregorio562b7312011-09-15 09:06:38 -040072
Joe Gregoriod92897c2011-07-07 11:44:56 -040073def _fix_method_name(name):
74 if name in RESERVED_WORDS:
75 return name + '_'
76 else:
77 return name
Joe Gregorio48d361f2010-08-18 13:19:21 -040078
Joe Gregorioa98733f2011-09-16 10:12:28 -040079
Joe Gregorio922b78c2011-05-26 21:36:34 -040080def _write_headers(self):
81 # Utility no-op method for multipart media handling
82 pass
83
84
Joe Gregorioa98733f2011-09-16 10:12:28 -040085def _add_query_parameter(url, name, value):
86 """Adds a query parameter to a url
87
88 Args:
89 url: string, url to add the query parameter to.
90 name: string, query parameter name.
91 value: string, query parameter value.
92
93 Returns:
94 Updated query parameter. Does not update the url if value is None.
95 """
96 if value is None:
97 return url
98 else:
99 parsed = list(urlparse.urlparse(url))
100 q = parse_qsl(parsed[4])
101 q.append((name, value))
102 parsed[4] = urllib.urlencode(q)
103 return urlparse.urlunparse(parsed)
104
105
Joe Gregorio48d361f2010-08-18 13:19:21 -0400106def key2param(key):
Joe Gregorio7c22ab22011-02-16 15:32:39 -0500107 """Converts key names into parameter names.
108
109 For example, converting "max-results" -> "max_results"
Joe Gregorio48d361f2010-08-18 13:19:21 -0400110 """
111 result = []
112 key = list(key)
113 if not key[0].isalpha():
114 result.append('x')
115 for c in key:
116 if c.isalnum():
117 result.append(c)
118 else:
119 result.append('_')
120
121 return ''.join(result)
122
123
Joe Gregorioaf276d22010-12-09 14:26:58 -0500124def build(serviceName, version,
Joe Gregorio3fada332011-01-07 17:07:45 -0500125 http=None,
126 discoveryServiceUrl=DISCOVERY_URI,
127 developerKey=None,
Joe Gregoriod433b2a2011-02-22 10:51:51 -0500128 model=None,
Joe Gregorio3fada332011-01-07 17:07:45 -0500129 requestBuilder=HttpRequest):
Joe Gregorioabda96f2011-02-11 20:19:33 -0500130 """Construct a Resource for interacting with an API.
131
132 Construct a Resource object for interacting with
133 an API. The serviceName and version are the
134 names from the Discovery service.
135
136 Args:
137 serviceName: string, name of the service
138 version: string, the version of the service
139 discoveryServiceUrl: string, a URI Template that points to
140 the location of the discovery service. It should have two
141 parameters {api} and {apiVersion} that when filled in
142 produce an absolute URI to the discovery document for
143 that service.
Joe Gregoriodeeb0202011-02-15 14:49:57 -0500144 developerKey: string, key obtained
145 from https://code.google.com/apis/console
Joe Gregorioabda96f2011-02-11 20:19:33 -0500146 model: apiclient.Model, converts to and from the wire format
Joe Gregoriodeeb0202011-02-15 14:49:57 -0500147 requestBuilder: apiclient.http.HttpRequest, encapsulator for
148 an HTTP request
Joe Gregorioabda96f2011-02-11 20:19:33 -0500149
150 Returns:
151 A Resource object with methods for interacting with
152 the service.
153 """
Joe Gregorio48d361f2010-08-18 13:19:21 -0400154 params = {
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400155 'api': serviceName,
Joe Gregorio48d361f2010-08-18 13:19:21 -0400156 'apiVersion': version
157 }
ade@google.com850cf552010-08-20 23:24:56 +0100158
Joe Gregorioc204b642010-09-21 12:01:23 -0400159 if http is None:
160 http = httplib2.Http()
Joe Gregorioa98733f2011-09-16 10:12:28 -0400161
ade@google.com850cf552010-08-20 23:24:56 +0100162 requested_url = uritemplate.expand(discoveryServiceUrl, params)
Joe Gregorio583d9e42011-09-16 15:54:15 -0400163
Joe Gregorio66f57522011-11-30 11:00:00 -0500164 # REMOTE_ADDR is defined by the CGI spec [RFC3875] as the environment
165 # variable that contains the network address of the client sending the
166 # request. If it exists then add that to the request for the discovery
167 # document to avoid exceeding the quota on discovery requests.
Joe Gregorio583d9e42011-09-16 15:54:15 -0400168 if 'REMOTE_ADDR' in os.environ:
169 requested_url = _add_query_parameter(requested_url, 'userIp',
170 os.environ['REMOTE_ADDR'])
ade@google.com850cf552010-08-20 23:24:56 +0100171 logging.info('URL being requested: %s' % requested_url)
Joe Gregorioa98733f2011-09-16 10:12:28 -0400172
ade@google.com850cf552010-08-20 23:24:56 +0100173 resp, content = http.request(requested_url)
Joe Gregorioa98733f2011-09-16 10:12:28 -0400174
Joe Gregorio8b4df3f2011-11-18 15:44:48 -0500175 if resp.status == 404:
Joe Gregoriodae2f552011-11-21 08:16:56 -0500176 raise UnknownApiNameOrVersion("name: %s version: %s" % (serviceName,
Joe Gregorio8b4df3f2011-11-18 15:44:48 -0500177 version))
Joe Gregorioa98733f2011-09-16 10:12:28 -0400178 if resp.status >= 400:
Joe Gregorio49396552011-03-08 10:39:00 -0500179 raise HttpError(resp, content, requested_url)
Joe Gregorioa98733f2011-09-16 10:12:28 -0400180
Joe Gregorioc0e0fe92011-03-04 16:16:55 -0500181 try:
182 service = simplejson.loads(content)
183 except ValueError, e:
Joe Gregorio205e73a2011-03-12 09:55:31 -0500184 logging.error('Failed to parse as JSON: ' + content)
Joe Gregorio49396552011-03-08 10:39:00 -0500185 raise InvalidJsonError()
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400186
Joe Gregorioa98733f2011-09-16 10:12:28 -0400187 filename = os.path.join(os.path.dirname(__file__), 'contrib',
Joe Gregorio7c22ab22011-02-16 15:32:39 -0500188 serviceName, 'future.json')
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400189 try:
Joe Gregorioa98733f2011-09-16 10:12:28 -0400190 f = file(filename, 'r')
Joe Gregorio292b9b82011-01-12 11:36:11 -0500191 future = f.read()
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400192 f.close()
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400193 except IOError:
Joe Gregorio292b9b82011-01-12 11:36:11 -0500194 future = None
195
196 return build_from_document(content, discoveryServiceUrl, future,
197 http, developerKey, model, requestBuilder)
198
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500199
Joe Gregorio292b9b82011-01-12 11:36:11 -0500200def build_from_document(
201 service,
202 base,
203 future=None,
204 http=None,
205 developerKey=None,
Joe Gregoriod433b2a2011-02-22 10:51:51 -0500206 model=None,
Joe Gregorio292b9b82011-01-12 11:36:11 -0500207 requestBuilder=HttpRequest):
Joe Gregorioabda96f2011-02-11 20:19:33 -0500208 """Create a Resource for interacting with an API.
209
210 Same as `build()`, but constructs the Resource object
211 from a discovery document that is it given, as opposed to
212 retrieving one over HTTP.
213
Joe Gregorio292b9b82011-01-12 11:36:11 -0500214 Args:
215 service: string, discovery document
216 base: string, base URI for all HTTP requests, usually the discovery URI
217 future: string, discovery document with future capabilities
218 auth_discovery: dict, information about the authentication the API supports
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500219 http: httplib2.Http, An instance of httplib2.Http or something that acts
220 like it that HTTP requests will be made through.
Joe Gregorio292b9b82011-01-12 11:36:11 -0500221 developerKey: string, Key for controlling API usage, generated
222 from the API Console.
223 model: Model class instance that serializes and
224 de-serializes requests and responses.
225 requestBuilder: Takes an http request and packages it up to be executed.
Joe Gregorioabda96f2011-02-11 20:19:33 -0500226
227 Returns:
228 A Resource object with methods for interacting with
229 the service.
Joe Gregorio292b9b82011-01-12 11:36:11 -0500230 """
231
232 service = simplejson.loads(service)
Joe Gregorio6a63a762011-05-02 22:36:05 -0400233 base = urlparse.urljoin(base, service['basePath'])
Joe Gregorio292b9b82011-01-12 11:36:11 -0500234 if future:
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500235 future = simplejson.loads(future)
236 auth_discovery = future.get('auth', {})
Joe Gregorio292b9b82011-01-12 11:36:11 -0500237 else:
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400238 future = {}
239 auth_discovery = {}
Joe Gregorio3c676f92011-07-25 10:38:14 -0400240 schema = service.get('schemas', {})
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400241
Joe Gregoriod433b2a2011-02-22 10:51:51 -0500242 if model is None:
Joe Gregoriof863f7a2011-02-24 03:24:44 -0500243 features = service.get('features', [])
Joe Gregorio266c6442011-02-23 16:08:54 -0500244 model = JsonModel('dataWrapper' in features)
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500245 resource = createResource(http, base, model, requestBuilder, developerKey,
Joe Gregorio3c676f92011-07-25 10:38:14 -0400246 service, future, schema)
Joe Gregorio48d361f2010-08-18 13:19:21 -0400247
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500248 def auth_method():
249 """Discovery information about the authentication the API uses."""
250 return auth_discovery
Joe Gregorio48d361f2010-08-18 13:19:21 -0400251
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500252 setattr(resource, 'auth_discovery', auth_method)
Joe Gregorioa2f56e72010-09-09 15:15:56 -0400253
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500254 return resource
Joe Gregorio48d361f2010-08-18 13:19:21 -0400255
256
Joe Gregorio61d7e962011-02-22 22:52:07 -0500257def _cast(value, schema_type):
Joe Gregoriobee86832011-02-22 10:00:19 -0500258 """Convert value to a string based on JSON Schema type.
259
260 See http://tools.ietf.org/html/draft-zyp-json-schema-03 for more details on
261 JSON Schema.
262
263 Args:
264 value: any, the value to convert
265 schema_type: string, the type that value should be interpreted as
266
267 Returns:
268 A string representation of 'value' based on the schema_type.
269 """
270 if schema_type == 'string':
Joe Gregoriof863f7a2011-02-24 03:24:44 -0500271 if type(value) == type('') or type(value) == type(u''):
272 return value
273 else:
274 return str(value)
Joe Gregoriobee86832011-02-22 10:00:19 -0500275 elif schema_type == 'integer':
276 return str(int(value))
277 elif schema_type == 'number':
278 return str(float(value))
279 elif schema_type == 'boolean':
280 return str(bool(value)).lower()
281 else:
Joe Gregoriof863f7a2011-02-24 03:24:44 -0500282 if type(value) == type('') or type(value) == type(u''):
283 return value
284 else:
285 return str(value)
Joe Gregoriobee86832011-02-22 10:00:19 -0500286
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400287MULTIPLIERS = {
Joe Gregorio562b7312011-09-15 09:06:38 -0400288 "KB": 2 ** 10,
289 "MB": 2 ** 20,
290 "GB": 2 ** 30,
291 "TB": 2 ** 40,
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400292 }
293
Joe Gregorioa98733f2011-09-16 10:12:28 -0400294
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400295def _media_size_to_long(maxSize):
296 """Convert a string media size, such as 10GB or 3TB into an integer."""
Joe Gregorio84d3c1f2011-07-25 10:39:45 -0400297 if len(maxSize) < 2:
298 return 0
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400299 units = maxSize[-2:].upper()
300 multiplier = MULTIPLIERS.get(units, 0)
301 if multiplier:
Joe Gregorio562b7312011-09-15 09:06:38 -0400302 return int(maxSize[:-2]) * multiplier
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400303 else:
304 return int(maxSize)
305
Joe Gregoriobee86832011-02-22 10:00:19 -0500306
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500307def createResource(http, baseUrl, model, requestBuilder,
Joe Gregorio3c676f92011-07-25 10:38:14 -0400308 developerKey, resourceDesc, futureDesc, schema):
Joe Gregorio48d361f2010-08-18 13:19:21 -0400309
310 class Resource(object):
311 """A class for interacting with a resource."""
312
313 def __init__(self):
314 self._http = http
315 self._baseUrl = baseUrl
316 self._model = model
Joe Gregorio00cf1d92010-09-27 09:22:03 -0400317 self._developerKey = developerKey
Joe Gregorioaf276d22010-12-09 14:26:58 -0500318 self._requestBuilder = requestBuilder
Joe Gregorio48d361f2010-08-18 13:19:21 -0400319
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400320 def createMethod(theclass, methodName, methodDesc, futureDesc):
Joe Gregoriod92897c2011-07-07 11:44:56 -0400321 methodName = _fix_method_name(methodName)
Joe Gregorio6a63a762011-05-02 22:36:05 -0400322 pathUrl = methodDesc['path']
Joe Gregorio48d361f2010-08-18 13:19:21 -0400323 httpMethod = methodDesc['httpMethod']
Joe Gregorio6a63a762011-05-02 22:36:05 -0400324 methodId = methodDesc['id']
Joe Gregorio21f11672010-08-18 17:23:17 -0400325
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400326 mediaPathUrl = None
327 accept = []
328 maxSize = 0
329 if 'mediaUpload' in methodDesc:
330 mediaUpload = methodDesc['mediaUpload']
331 mediaPathUrl = mediaUpload['protocols']['simple']['path']
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500332 mediaResumablePathUrl = mediaUpload['protocols']['resumable']['path']
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400333 accept = mediaUpload['accept']
Joe Gregorio84d3c1f2011-07-25 10:39:45 -0400334 maxSize = _media_size_to_long(mediaUpload.get('maxSize', ''))
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400335
Joe Gregorioca876e42011-02-22 19:39:42 -0500336 if 'parameters' not in methodDesc:
337 methodDesc['parameters'] = {}
338 for name in STACK_QUERY_PARAMETERS:
339 methodDesc['parameters'][name] = {
340 'type': 'string',
Joe Gregorio6a63a762011-05-02 22:36:05 -0400341 'location': 'query'
Joe Gregorioca876e42011-02-22 19:39:42 -0500342 }
343
Joe Gregoriof4153422011-03-18 22:45:18 -0400344 if httpMethod in ['PUT', 'POST', 'PATCH']:
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500345 methodDesc['parameters']['body'] = {
346 'description': 'The request body.',
Joe Gregorioc2a73932011-02-22 10:17:06 -0500347 'type': 'object',
Joe Gregorio1ae3e742011-02-25 15:17:14 -0500348 'required': True,
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500349 }
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400350 if 'mediaUpload' in methodDesc:
351 methodDesc['parameters']['media_body'] = {
352 'description': 'The filename of the media request body.',
353 'type': 'string',
354 'required': False,
355 }
356 methodDesc['parameters']['body']['required'] = False
ade@google.com850cf552010-08-20 23:24:56 +0100357
Joe Gregorioca876e42011-02-22 19:39:42 -0500358 argmap = {} # Map from method parameter name to query parameter name
ade@google.com850cf552010-08-20 23:24:56 +0100359 required_params = [] # Required parameters
Joe Gregorio61d7e962011-02-22 22:52:07 -0500360 repeated_params = [] # Repeated parameters
ade@google.com850cf552010-08-20 23:24:56 +0100361 pattern_params = {} # Parameters that must match a regex
362 query_params = [] # Parameters that will be used in the query string
363 path_params = {} # Parameters that will be used in the base URL
Joe Gregoriobee86832011-02-22 10:00:19 -0500364 param_type = {} # The type of the parameter
Joe Gregorioca876e42011-02-22 19:39:42 -0500365 enum_params = {} # Allowable enumeration values for each parameter
366
367
Joe Gregorio4292c6e2010-09-09 14:32:43 -0400368 if 'parameters' in methodDesc:
369 for arg, desc in methodDesc['parameters'].iteritems():
370 param = key2param(arg)
371 argmap[param] = arg
Joe Gregorio21f11672010-08-18 17:23:17 -0400372
Joe Gregorio4292c6e2010-09-09 14:32:43 -0400373 if desc.get('pattern', ''):
374 pattern_params[param] = desc['pattern']
Joe Gregoriobee86832011-02-22 10:00:19 -0500375 if desc.get('enum', ''):
376 enum_params[param] = desc['enum']
Joe Gregorio4292c6e2010-09-09 14:32:43 -0400377 if desc.get('required', False):
378 required_params.append(param)
Joe Gregorio61d7e962011-02-22 22:52:07 -0500379 if desc.get('repeated', False):
380 repeated_params.append(param)
Joe Gregorio6a63a762011-05-02 22:36:05 -0400381 if desc.get('location') == 'query':
Joe Gregorio4292c6e2010-09-09 14:32:43 -0400382 query_params.append(param)
Joe Gregorio6a63a762011-05-02 22:36:05 -0400383 if desc.get('location') == 'path':
Joe Gregorio4292c6e2010-09-09 14:32:43 -0400384 path_params[param] = param
Joe Gregoriobee86832011-02-22 10:00:19 -0500385 param_type[param] = desc.get('type', 'string')
Joe Gregorio48d361f2010-08-18 13:19:21 -0400386
Joe Gregoriobc2ff9b2010-11-08 09:20:48 -0500387 for match in URITEMPLATE.finditer(pathUrl):
388 for namematch in VARNAME.finditer(match.group(0)):
389 name = key2param(namematch.group(0))
390 path_params[name] = name
391 if name in query_params:
392 query_params.remove(name)
393
Joe Gregorio48d361f2010-08-18 13:19:21 -0400394 def method(self, **kwargs):
395 for name in kwargs.iterkeys():
Joe Gregorioca876e42011-02-22 19:39:42 -0500396 if name not in argmap:
Joe Gregorio48d361f2010-08-18 13:19:21 -0400397 raise TypeError('Got an unexpected keyword argument "%s"' % name)
Joe Gregorio21f11672010-08-18 17:23:17 -0400398
ade@google.com850cf552010-08-20 23:24:56 +0100399 for name in required_params:
Joe Gregoriofbf9d0d2010-08-18 16:50:47 -0400400 if name not in kwargs:
401 raise TypeError('Missing required parameter "%s"' % name)
Joe Gregorio21f11672010-08-18 17:23:17 -0400402
ade@google.com850cf552010-08-20 23:24:56 +0100403 for name, regex in pattern_params.iteritems():
Joe Gregorio21f11672010-08-18 17:23:17 -0400404 if name in kwargs:
Joe Gregorio6804c7a2011-11-18 14:30:32 -0500405 if isinstance(kwargs[name], basestring):
406 pvalues = [kwargs[name]]
407 else:
408 pvalues = kwargs[name]
409 for pvalue in pvalues:
410 if re.match(regex, pvalue) is None:
411 raise TypeError(
412 'Parameter "%s" value "%s" does not match the pattern "%s"' %
413 (name, pvalue, regex))
Joe Gregorio21f11672010-08-18 17:23:17 -0400414
Joe Gregoriobee86832011-02-22 10:00:19 -0500415 for name, enums in enum_params.iteritems():
416 if name in kwargs:
417 if kwargs[name] not in enums:
418 raise TypeError(
Joe Gregorioca876e42011-02-22 19:39:42 -0500419 'Parameter "%s" value "%s" is not an allowed value in "%s"' %
Joe Gregoriobee86832011-02-22 10:00:19 -0500420 (name, kwargs[name], str(enums)))
421
ade@google.com850cf552010-08-20 23:24:56 +0100422 actual_query_params = {}
423 actual_path_params = {}
Joe Gregorio21f11672010-08-18 17:23:17 -0400424 for key, value in kwargs.iteritems():
Joe Gregorio61d7e962011-02-22 22:52:07 -0500425 to_type = param_type.get(key, 'string')
426 # For repeated parameters we cast each member of the list.
427 if key in repeated_params and type(value) == type([]):
428 cast_value = [_cast(x, to_type) for x in value]
429 else:
430 cast_value = _cast(value, to_type)
ade@google.com850cf552010-08-20 23:24:56 +0100431 if key in query_params:
Joe Gregorio61d7e962011-02-22 22:52:07 -0500432 actual_query_params[argmap[key]] = cast_value
ade@google.com850cf552010-08-20 23:24:56 +0100433 if key in path_params:
Joe Gregorio61d7e962011-02-22 22:52:07 -0500434 actual_path_params[argmap[key]] = cast_value
ade@google.com850cf552010-08-20 23:24:56 +0100435 body_value = kwargs.get('body', None)
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400436 media_filename = kwargs.get('media_body', None)
Joe Gregorio21f11672010-08-18 17:23:17 -0400437
Joe Gregorio00cf1d92010-09-27 09:22:03 -0400438 if self._developerKey:
439 actual_query_params['key'] = self._developerKey
440
Joe Gregorioe08a1662011-12-07 09:48:22 -0500441 model = self._model
442 # If there is no schema for the response then presume a binary blob.
443 if 'response' not in methodDesc:
444 model = RawModel()
445
Joe Gregorio48d361f2010-08-18 13:19:21 -0400446 headers = {}
Joe Gregorioe08a1662011-12-07 09:48:22 -0500447 headers, params, query, body = model.request(headers,
Joe Gregorio3bbbf662010-08-30 16:41:53 -0400448 actual_path_params, actual_query_params, body_value)
Joe Gregorio48d361f2010-08-18 13:19:21 -0400449
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400450 expanded_url = uritemplate.expand(pathUrl, params)
Joe Gregorio922b78c2011-05-26 21:36:34 -0400451 url = urlparse.urljoin(self._baseUrl, expanded_url + query)
452
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500453 resumable = None
454 multipart_boundary = ''
455
Joe Gregorio922b78c2011-05-26 21:36:34 -0400456 if media_filename:
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500457 # Convert a simple filename into a MediaUpload object.
458 if isinstance(media_filename, basestring):
459 (media_mime_type, encoding) = mimetypes.guess_type(media_filename)
460 if media_mime_type is None:
461 raise UnknownFileType(media_filename)
462 if not mimeparse.best_match([media_mime_type], ','.join(accept)):
463 raise UnacceptableMimeTypeError(media_mime_type)
464 media_upload = MediaFileUpload(media_filename, media_mime_type)
465 elif isinstance(media_filename, MediaUpload):
466 media_upload = media_filename
467 else:
Joe Gregorio66f57522011-11-30 11:00:00 -0500468 raise TypeError('media_filename must be str or MediaUpload.')
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500469
470 if media_upload.resumable():
471 resumable = media_upload
Joe Gregorio922b78c2011-05-26 21:36:34 -0400472
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400473 # Check the maxSize
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500474 if maxSize > 0 and media_upload.size() > maxSize:
475 raise MediaUploadSizeError("Media larger than: %s" % maxSize)
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400476
477 # Use the media path uri for media uploads
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500478 if media_upload.resumable():
479 expanded_url = uritemplate.expand(mediaResumablePathUrl, params)
480 else:
481 expanded_url = uritemplate.expand(mediaPathUrl, params)
Joe Gregoriofdf7c802011-06-30 12:33:38 -0400482 url = urlparse.urljoin(self._baseUrl, expanded_url + query)
Joe Gregorio922b78c2011-05-26 21:36:34 -0400483
484 if body is None:
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500485 # This is a simple media upload
486 headers['content-type'] = media_upload.mimetype()
487 expanded_url = uritemplate.expand(mediaResumablePathUrl, params)
488 if not media_upload.resumable():
489 body = media_upload.getbytes(0, media_upload.size())
Joe Gregorio922b78c2011-05-26 21:36:34 -0400490 else:
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500491 # This is a multipart/related upload.
Joe Gregorio922b78c2011-05-26 21:36:34 -0400492 msgRoot = MIMEMultipart('related')
493 # msgRoot should not write out it's own headers
494 setattr(msgRoot, '_write_headers', lambda self: None)
495
496 # attach the body as one part
497 msg = MIMENonMultipart(*headers['content-type'].split('/'))
498 msg.set_payload(body)
499 msgRoot.attach(msg)
500
501 # attach the media as the second part
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500502 msg = MIMENonMultipart(*media_upload.mimetype().split('/'))
Joe Gregorio922b78c2011-05-26 21:36:34 -0400503 msg['Content-Transfer-Encoding'] = 'binary'
504
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500505 if media_upload.resumable():
506 # This is a multipart resumable upload, where a multipart payload
507 # looks like this:
508 #
509 # --===============1678050750164843052==
510 # Content-Type: application/json
511 # MIME-Version: 1.0
512 #
513 # {'foo': 'bar'}
514 # --===============1678050750164843052==
515 # Content-Type: image/png
516 # MIME-Version: 1.0
517 # Content-Transfer-Encoding: binary
518 #
519 # <BINARY STUFF>
520 # --===============1678050750164843052==--
521 #
522 # In the case of resumable multipart media uploads, the <BINARY
523 # STUFF> is large and will be spread across multiple PUTs. What we
524 # do here is compose the multipart message with a random payload in
525 # place of <BINARY STUFF> and then split the resulting content into
526 # two pieces, text before <BINARY STUFF> and text after <BINARY
527 # STUFF>. The text after <BINARY STUFF> is the multipart boundary.
528 # In apiclient.http the HttpRequest will send the text before
529 # <BINARY STUFF>, then send the actual binary media in chunks, and
530 # then will send the multipart delimeter.
Joe Gregorio922b78c2011-05-26 21:36:34 -0400531
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500532 payload = hex(random.getrandbits(300))
533 msg.set_payload(payload)
534 msgRoot.attach(msg)
535 body = msgRoot.as_string()
536 body, _ = body.split(payload)
537 resumable = media_upload
538 else:
539 payload = media_upload.getbytes(0, media_upload.size())
540 msg.set_payload(payload)
541 msgRoot.attach(msg)
542 body = msgRoot.as_string()
Joe Gregorio922b78c2011-05-26 21:36:34 -0400543
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500544 multipart_boundary = msgRoot.get_boundary()
Joe Gregorio922b78c2011-05-26 21:36:34 -0400545 headers['content-type'] = ('multipart/related; '
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500546 'boundary="%s"') % multipart_boundary
Joe Gregoriofbf9d0d2010-08-18 16:50:47 -0400547
ade@google.com850cf552010-08-20 23:24:56 +0100548 logging.info('URL being requested: %s' % url)
Joe Gregorioabda96f2011-02-11 20:19:33 -0500549 return self._requestBuilder(self._http,
Joe Gregorioe08a1662011-12-07 09:48:22 -0500550 model.response,
Joe Gregorioabda96f2011-02-11 20:19:33 -0500551 url,
552 method=httpMethod,
553 body=body,
Joe Gregorioaf276d22010-12-09 14:26:58 -0500554 headers=headers,
Joe Gregoriod0bd3882011-11-22 09:49:47 -0500555 methodId=methodId,
556 resumable=resumable)
Joe Gregorio48d361f2010-08-18 13:19:21 -0400557
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500558 docs = [methodDesc.get('description', DEFAULT_METHOD_DOC), '\n\n']
559 if len(argmap) > 0:
Joe Gregorio61d7e962011-02-22 22:52:07 -0500560 docs.append('Args:\n')
Joe Gregorio48d361f2010-08-18 13:19:21 -0400561 for arg in argmap.iterkeys():
Joe Gregorioca876e42011-02-22 19:39:42 -0500562 if arg in STACK_QUERY_PARAMETERS:
563 continue
Joe Gregorio61d7e962011-02-22 22:52:07 -0500564 repeated = ''
565 if arg in repeated_params:
566 repeated = ' (repeated)'
567 required = ''
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400568 if arg in required_params:
Joe Gregorio61d7e962011-02-22 22:52:07 -0500569 required = ' (required)'
Joe Gregorioc2a73932011-02-22 10:17:06 -0500570 paramdesc = methodDesc['parameters'][argmap[arg]]
571 paramdoc = paramdesc.get('description', 'A parameter')
572 paramtype = paramdesc.get('type', 'string')
Joe Gregorio61d7e962011-02-22 22:52:07 -0500573 docs.append(' %s: %s, %s%s%s\n' % (arg, paramtype, paramdoc, required,
574 repeated))
Joe Gregorioc2a73932011-02-22 10:17:06 -0500575 enum = paramdesc.get('enum', [])
576 enumDesc = paramdesc.get('enumDescriptions', [])
577 if enum and enumDesc:
578 docs.append(' Allowed values\n')
579 for (name, desc) in zip(enum, enumDesc):
580 docs.append(' %s - %s\n' % (name, desc))
Joe Gregorio48d361f2010-08-18 13:19:21 -0400581
582 setattr(method, '__doc__', ''.join(docs))
583 setattr(theclass, methodName, method)
584
Joe Gregorio3c676f92011-07-25 10:38:14 -0400585 def createNextMethodFromFuture(theclass, methodName, methodDesc, futureDesc):
Joe Gregorioa98733f2011-09-16 10:12:28 -0400586 """ This is a legacy method, as only Buzz and Moderator use the future.json
587 functionality for generating _next methods. It will be kept around as long
588 as those API versions are around, but no new APIs should depend upon it.
589 """
Joe Gregoriod92897c2011-07-07 11:44:56 -0400590 methodName = _fix_method_name(methodName)
Joe Gregorio6a63a762011-05-02 22:36:05 -0400591 methodId = methodDesc['id'] + '.next'
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400592
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500593 def methodNext(self, previous):
Joe Gregorioa98733f2011-09-16 10:12:28 -0400594 """Retrieve the next page of results.
595
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400596 Takes a single argument, 'body', which is the results
597 from the last call, and returns the next set of items
598 in the collection.
599
Joe Gregorioa98733f2011-09-16 10:12:28 -0400600 Returns:
601 None if there are no more items in the collection.
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400602 """
Joe Gregorioaf276d22010-12-09 14:26:58 -0500603 if futureDesc['type'] != 'uri':
604 raise UnknownLinkType(futureDesc['type'])
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400605
606 try:
607 p = previous
Joe Gregorioaf276d22010-12-09 14:26:58 -0500608 for key in futureDesc['location']:
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400609 p = p[key]
610 url = p
Joe Gregorioc5c5a372010-09-22 11:42:32 -0400611 except (KeyError, TypeError):
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400612 return None
613
Joe Gregorioa98733f2011-09-16 10:12:28 -0400614 url = _add_query_parameter(url, 'key', self._developerKey)
Joe Gregorio00cf1d92010-09-27 09:22:03 -0400615
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400616 headers = {}
617 headers, params, query, body = self._model.request(headers, {}, {}, None)
618
619 logging.info('URL being requested: %s' % url)
620 resp, content = self._http.request(url, method='GET', headers=headers)
621
Joe Gregorioabda96f2011-02-11 20:19:33 -0500622 return self._requestBuilder(self._http,
623 self._model.response,
624 url,
625 method='GET',
Joe Gregorioaf276d22010-12-09 14:26:58 -0500626 headers=headers,
Joe Gregorioaf276d22010-12-09 14:26:58 -0500627 methodId=methodId)
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400628
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500629 setattr(theclass, methodName, methodNext)
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400630
Joe Gregorio3c676f92011-07-25 10:38:14 -0400631 def createNextMethod(theclass, methodName, methodDesc, futureDesc):
632 methodName = _fix_method_name(methodName)
633 methodId = methodDesc['id'] + '.next'
634
635 def methodNext(self, previous_request, previous_response):
636 """Retrieves the next page of results.
637
638 Args:
639 previous_request: The request for the previous page.
640 previous_response: The response from the request for the previous page.
641
642 Returns:
643 A request object that you can call 'execute()' on to request the next
644 page. Returns None if there are no more items in the collection.
645 """
646 # Retrieve nextPageToken from previous_response
647 # Use as pageToken in previous_request to create new request.
648
649 if 'nextPageToken' not in previous_response:
650 return None
651
652 request = copy.copy(previous_request)
653
654 pageToken = previous_response['nextPageToken']
655 parsed = list(urlparse.urlparse(request.uri))
656 q = parse_qsl(parsed[4])
657
658 # Find and remove old 'pageToken' value from URI
659 newq = [(key, value) for (key, value) in q if key != 'pageToken']
660 newq.append(('pageToken', pageToken))
661 parsed[4] = urllib.urlencode(newq)
662 uri = urlparse.urlunparse(parsed)
663
664 request.uri = uri
665
666 logging.info('URL being requested: %s' % uri)
667
668 return request
669
670 setattr(theclass, methodName, methodNext)
671
672
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400673 # Add basic methods to Resource
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400674 if 'methods' in resourceDesc:
675 for methodName, methodDesc in resourceDesc['methods'].iteritems():
676 if futureDesc:
677 future = futureDesc['methods'].get(methodName, {})
678 else:
679 future = None
680 createMethod(Resource, methodName, methodDesc, future)
681
682 # Add in nested resources
683 if 'resources' in resourceDesc:
Joe Gregorioaf276d22010-12-09 14:26:58 -0500684
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500685 def createResourceMethod(theclass, methodName, methodDesc, futureDesc):
Joe Gregoriod92897c2011-07-07 11:44:56 -0400686 methodName = _fix_method_name(methodName)
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400687
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500688 def methodResource(self):
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400689 return createResource(self._http, self._baseUrl, self._model,
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500690 self._requestBuilder, self._developerKey,
Joe Gregorio3c676f92011-07-25 10:38:14 -0400691 methodDesc, futureDesc, schema)
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400692
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500693 setattr(methodResource, '__doc__', 'A collection resource.')
694 setattr(methodResource, '__is_resource__', True)
695 setattr(theclass, methodName, methodResource)
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400696
697 for methodName, methodDesc in resourceDesc['resources'].iteritems():
698 if futureDesc and 'resources' in futureDesc:
699 future = futureDesc['resources'].get(methodName, {})
700 else:
701 future = {}
Joe Gregorioc3fae8a2011-02-18 14:19:50 -0500702 createResourceMethod(Resource, methodName, methodDesc, future)
Joe Gregorio6d5e94f2010-08-25 23:49:30 -0400703
704 # Add <m>_next() methods to Resource
Joe Gregorio7a6df3a2011-01-31 21:55:21 -0500705 if futureDesc and 'methods' in futureDesc:
Joe Gregorio2379ecc2010-10-26 10:51:28 -0400706 for methodName, methodDesc in futureDesc['methods'].iteritems():
707 if 'next' in methodDesc and methodName in resourceDesc['methods']:
Joe Gregorio3c676f92011-07-25 10:38:14 -0400708 createNextMethodFromFuture(Resource, methodName + '_next',
Joe Gregorioaf276d22010-12-09 14:26:58 -0500709 resourceDesc['methods'][methodName],
710 methodDesc['next'])
Joe Gregorio3c676f92011-07-25 10:38:14 -0400711 # Add _next() methods
712 # Look for response bodies in schema that contain nextPageToken, and methods
713 # that take a pageToken parameter.
714 if 'methods' in resourceDesc:
715 for methodName, methodDesc in resourceDesc['methods'].iteritems():
716 if 'response' in methodDesc:
717 responseSchema = methodDesc['response']
718 if '$ref' in responseSchema:
719 responseSchema = schema[responseSchema['$ref']]
Joe Gregorio555f33c2011-08-19 14:56:07 -0400720 hasNextPageToken = 'nextPageToken' in responseSchema.get('properties',
721 {})
Joe Gregorio3c676f92011-07-25 10:38:14 -0400722 hasPageToken = 'pageToken' in methodDesc.get('parameters', {})
723 if hasNextPageToken and hasPageToken:
724 createNextMethod(Resource, methodName + '_next',
725 resourceDesc['methods'][methodName],
726 methodName)
Joe Gregorio48d361f2010-08-18 13:19:21 -0400727
728 return Resource()