Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 1 | # 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 Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 17 | A client library for Google's discovery based APIs. |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 18 | """ |
| 19 | |
| 20 | __author__ = 'jcgregorio@google.com (Joe Gregorio)' |
Joe Gregorio | abda96f | 2011-02-11 20:19:33 -0500 | [diff] [blame] | 21 | __all__ = [ |
| 22 | 'build', 'build_from_document' |
| 23 | ] |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 24 | |
| 25 | import httplib2 |
ade@google.com | 850cf55 | 2010-08-20 23:24:56 +0100 | [diff] [blame] | 26 | import logging |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 27 | import os |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 28 | import re |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 29 | import uritemplate |
Joe Gregorio | fe695fb | 2010-08-30 12:04:04 -0400 | [diff] [blame] | 30 | import urllib |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 31 | import urlparse |
Joe Gregorio | fdf7c80 | 2011-06-30 12:33:38 -0400 | [diff] [blame] | 32 | import mimeparse |
Joe Gregorio | 922b78c | 2011-05-26 21:36:34 -0400 | [diff] [blame] | 33 | import mimetypes |
| 34 | |
ade@google.com | c5eb46f | 2010-09-27 23:35:39 +0100 | [diff] [blame] | 35 | try: |
| 36 | from urlparse import parse_qsl |
| 37 | except ImportError: |
| 38 | from cgi import parse_qsl |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 39 | |
Joe Gregorio | 034e700 | 2010-12-15 08:45:03 -0500 | [diff] [blame] | 40 | from anyjson import simplejson |
Joe Gregorio | 922b78c | 2011-05-26 21:36:34 -0400 | [diff] [blame] | 41 | from email.mime.multipart import MIMEMultipart |
| 42 | from email.mime.nonmultipart import MIMENonMultipart |
Joe Gregorio | c0e0fe9 | 2011-03-04 16:16:55 -0500 | [diff] [blame] | 43 | from errors import HttpError |
Joe Gregorio | 4939655 | 2011-03-08 10:39:00 -0500 | [diff] [blame] | 44 | from errors import InvalidJsonError |
Joe Gregorio | fdf7c80 | 2011-06-30 12:33:38 -0400 | [diff] [blame] | 45 | from errors import MediaUploadSizeError |
| 46 | from errors import UnacceptableMimeTypeError |
Joe Gregorio | 922b78c | 2011-05-26 21:36:34 -0400 | [diff] [blame] | 47 | from errors import UnknownLinkType |
| 48 | from http import HttpRequest |
| 49 | from model import JsonModel |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 50 | |
Joe Gregorio | bc2ff9b | 2010-11-08 09:20:48 -0500 | [diff] [blame] | 51 | URITEMPLATE = re.compile('{[^}]*}') |
| 52 | VARNAME = re.compile('[a-zA-Z0-9_-]+') |
Joe Gregorio | 6a63a76 | 2011-05-02 22:36:05 -0400 | [diff] [blame] | 53 | DISCOVERY_URI = ('https://www.googleapis.com/discovery/v1/apis/' |
| 54 | '{api}/{apiVersion}/rest') |
Joe Gregorio | c3fae8a | 2011-02-18 14:19:50 -0500 | [diff] [blame] | 55 | DEFAULT_METHOD_DOC = 'A description of how to use this function' |
Joe Gregorio | ca876e4 | 2011-02-22 19:39:42 -0500 | [diff] [blame] | 56 | |
| 57 | # Query parameters that work, but don't appear in discovery |
Joe Gregorio | 06d852b | 2011-03-25 15:03:10 -0400 | [diff] [blame] | 58 | STACK_QUERY_PARAMETERS = ['trace', 'fields', 'pp', 'prettyPrint', 'userIp', |
Joe Gregorio | 3eecaa9 | 2011-05-17 13:40:12 -0400 | [diff] [blame] | 59 | 'userip', 'strict'] |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 60 | |
| 61 | |
Joe Gregorio | 922b78c | 2011-05-26 21:36:34 -0400 | [diff] [blame] | 62 | def _write_headers(self): |
| 63 | # Utility no-op method for multipart media handling |
| 64 | pass |
| 65 | |
| 66 | |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 67 | def key2param(key): |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 68 | """Converts key names into parameter names. |
| 69 | |
| 70 | For example, converting "max-results" -> "max_results" |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 71 | """ |
| 72 | result = [] |
| 73 | key = list(key) |
| 74 | if not key[0].isalpha(): |
| 75 | result.append('x') |
| 76 | for c in key: |
| 77 | if c.isalnum(): |
| 78 | result.append(c) |
| 79 | else: |
| 80 | result.append('_') |
| 81 | |
| 82 | return ''.join(result) |
| 83 | |
| 84 | |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 85 | def build(serviceName, version, |
Joe Gregorio | 3fada33 | 2011-01-07 17:07:45 -0500 | [diff] [blame] | 86 | http=None, |
| 87 | discoveryServiceUrl=DISCOVERY_URI, |
| 88 | developerKey=None, |
Joe Gregorio | d433b2a | 2011-02-22 10:51:51 -0500 | [diff] [blame] | 89 | model=None, |
Joe Gregorio | 3fada33 | 2011-01-07 17:07:45 -0500 | [diff] [blame] | 90 | requestBuilder=HttpRequest): |
Joe Gregorio | abda96f | 2011-02-11 20:19:33 -0500 | [diff] [blame] | 91 | """Construct a Resource for interacting with an API. |
| 92 | |
| 93 | Construct a Resource object for interacting with |
| 94 | an API. The serviceName and version are the |
| 95 | names from the Discovery service. |
| 96 | |
| 97 | Args: |
| 98 | serviceName: string, name of the service |
| 99 | version: string, the version of the service |
| 100 | discoveryServiceUrl: string, a URI Template that points to |
| 101 | the location of the discovery service. It should have two |
| 102 | parameters {api} and {apiVersion} that when filled in |
| 103 | produce an absolute URI to the discovery document for |
| 104 | that service. |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 105 | developerKey: string, key obtained |
| 106 | from https://code.google.com/apis/console |
Joe Gregorio | abda96f | 2011-02-11 20:19:33 -0500 | [diff] [blame] | 107 | model: apiclient.Model, converts to and from the wire format |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 108 | requestBuilder: apiclient.http.HttpRequest, encapsulator for |
| 109 | an HTTP request |
Joe Gregorio | abda96f | 2011-02-11 20:19:33 -0500 | [diff] [blame] | 110 | |
| 111 | Returns: |
| 112 | A Resource object with methods for interacting with |
| 113 | the service. |
| 114 | """ |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 115 | params = { |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 116 | 'api': serviceName, |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 117 | 'apiVersion': version |
| 118 | } |
ade@google.com | 850cf55 | 2010-08-20 23:24:56 +0100 | [diff] [blame] | 119 | |
Joe Gregorio | c204b64 | 2010-09-21 12:01:23 -0400 | [diff] [blame] | 120 | if http is None: |
| 121 | http = httplib2.Http() |
ade@google.com | 850cf55 | 2010-08-20 23:24:56 +0100 | [diff] [blame] | 122 | requested_url = uritemplate.expand(discoveryServiceUrl, params) |
| 123 | logging.info('URL being requested: %s' % requested_url) |
| 124 | resp, content = http.request(requested_url) |
Joe Gregorio | 4939655 | 2011-03-08 10:39:00 -0500 | [diff] [blame] | 125 | if resp.status > 400: |
| 126 | raise HttpError(resp, content, requested_url) |
Joe Gregorio | c0e0fe9 | 2011-03-04 16:16:55 -0500 | [diff] [blame] | 127 | try: |
| 128 | service = simplejson.loads(content) |
| 129 | except ValueError, e: |
Joe Gregorio | 205e73a | 2011-03-12 09:55:31 -0500 | [diff] [blame] | 130 | logging.error('Failed to parse as JSON: ' + content) |
Joe Gregorio | 4939655 | 2011-03-08 10:39:00 -0500 | [diff] [blame] | 131 | raise InvalidJsonError() |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 132 | |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 133 | fn = os.path.join(os.path.dirname(__file__), 'contrib', |
| 134 | serviceName, 'future.json') |
Joe Gregorio | 2379ecc | 2010-10-26 10:51:28 -0400 | [diff] [blame] | 135 | try: |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 136 | f = file(fn, 'r') |
Joe Gregorio | 292b9b8 | 2011-01-12 11:36:11 -0500 | [diff] [blame] | 137 | future = f.read() |
Joe Gregorio | 2379ecc | 2010-10-26 10:51:28 -0400 | [diff] [blame] | 138 | f.close() |
Joe Gregorio | 2379ecc | 2010-10-26 10:51:28 -0400 | [diff] [blame] | 139 | except IOError: |
Joe Gregorio | 292b9b8 | 2011-01-12 11:36:11 -0500 | [diff] [blame] | 140 | future = None |
| 141 | |
| 142 | return build_from_document(content, discoveryServiceUrl, future, |
| 143 | http, developerKey, model, requestBuilder) |
| 144 | |
Joe Gregorio | 7a6df3a | 2011-01-31 21:55:21 -0500 | [diff] [blame] | 145 | |
Joe Gregorio | 292b9b8 | 2011-01-12 11:36:11 -0500 | [diff] [blame] | 146 | def build_from_document( |
| 147 | service, |
| 148 | base, |
| 149 | future=None, |
| 150 | http=None, |
| 151 | developerKey=None, |
Joe Gregorio | d433b2a | 2011-02-22 10:51:51 -0500 | [diff] [blame] | 152 | model=None, |
Joe Gregorio | 292b9b8 | 2011-01-12 11:36:11 -0500 | [diff] [blame] | 153 | requestBuilder=HttpRequest): |
Joe Gregorio | abda96f | 2011-02-11 20:19:33 -0500 | [diff] [blame] | 154 | """Create a Resource for interacting with an API. |
| 155 | |
| 156 | Same as `build()`, but constructs the Resource object |
| 157 | from a discovery document that is it given, as opposed to |
| 158 | retrieving one over HTTP. |
| 159 | |
Joe Gregorio | 292b9b8 | 2011-01-12 11:36:11 -0500 | [diff] [blame] | 160 | Args: |
| 161 | service: string, discovery document |
| 162 | base: string, base URI for all HTTP requests, usually the discovery URI |
| 163 | future: string, discovery document with future capabilities |
| 164 | auth_discovery: dict, information about the authentication the API supports |
Joe Gregorio | 7a6df3a | 2011-01-31 21:55:21 -0500 | [diff] [blame] | 165 | http: httplib2.Http, An instance of httplib2.Http or something that acts |
| 166 | like it that HTTP requests will be made through. |
Joe Gregorio | 292b9b8 | 2011-01-12 11:36:11 -0500 | [diff] [blame] | 167 | developerKey: string, Key for controlling API usage, generated |
| 168 | from the API Console. |
| 169 | model: Model class instance that serializes and |
| 170 | de-serializes requests and responses. |
| 171 | requestBuilder: Takes an http request and packages it up to be executed. |
Joe Gregorio | abda96f | 2011-02-11 20:19:33 -0500 | [diff] [blame] | 172 | |
| 173 | Returns: |
| 174 | A Resource object with methods for interacting with |
| 175 | the service. |
Joe Gregorio | 292b9b8 | 2011-01-12 11:36:11 -0500 | [diff] [blame] | 176 | """ |
| 177 | |
| 178 | service = simplejson.loads(service) |
Joe Gregorio | 6a63a76 | 2011-05-02 22:36:05 -0400 | [diff] [blame] | 179 | base = urlparse.urljoin(base, service['basePath']) |
Joe Gregorio | 292b9b8 | 2011-01-12 11:36:11 -0500 | [diff] [blame] | 180 | if future: |
Joe Gregorio | 7a6df3a | 2011-01-31 21:55:21 -0500 | [diff] [blame] | 181 | future = simplejson.loads(future) |
| 182 | auth_discovery = future.get('auth', {}) |
Joe Gregorio | 292b9b8 | 2011-01-12 11:36:11 -0500 | [diff] [blame] | 183 | else: |
Joe Gregorio | 2379ecc | 2010-10-26 10:51:28 -0400 | [diff] [blame] | 184 | future = {} |
| 185 | auth_discovery = {} |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 186 | |
Joe Gregorio | d433b2a | 2011-02-22 10:51:51 -0500 | [diff] [blame] | 187 | if model is None: |
Joe Gregorio | f863f7a | 2011-02-24 03:24:44 -0500 | [diff] [blame] | 188 | features = service.get('features', []) |
Joe Gregorio | 266c644 | 2011-02-23 16:08:54 -0500 | [diff] [blame] | 189 | model = JsonModel('dataWrapper' in features) |
Joe Gregorio | 7a6df3a | 2011-01-31 21:55:21 -0500 | [diff] [blame] | 190 | resource = createResource(http, base, model, requestBuilder, developerKey, |
| 191 | service, future) |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 192 | |
Joe Gregorio | 7a6df3a | 2011-01-31 21:55:21 -0500 | [diff] [blame] | 193 | def auth_method(): |
| 194 | """Discovery information about the authentication the API uses.""" |
| 195 | return auth_discovery |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 196 | |
Joe Gregorio | 7a6df3a | 2011-01-31 21:55:21 -0500 | [diff] [blame] | 197 | setattr(resource, 'auth_discovery', auth_method) |
Joe Gregorio | a2f56e7 | 2010-09-09 15:15:56 -0400 | [diff] [blame] | 198 | |
Joe Gregorio | 7a6df3a | 2011-01-31 21:55:21 -0500 | [diff] [blame] | 199 | return resource |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 200 | |
| 201 | |
Joe Gregorio | 61d7e96 | 2011-02-22 22:52:07 -0500 | [diff] [blame] | 202 | def _cast(value, schema_type): |
Joe Gregorio | bee8683 | 2011-02-22 10:00:19 -0500 | [diff] [blame] | 203 | """Convert value to a string based on JSON Schema type. |
| 204 | |
| 205 | See http://tools.ietf.org/html/draft-zyp-json-schema-03 for more details on |
| 206 | JSON Schema. |
| 207 | |
| 208 | Args: |
| 209 | value: any, the value to convert |
| 210 | schema_type: string, the type that value should be interpreted as |
| 211 | |
| 212 | Returns: |
| 213 | A string representation of 'value' based on the schema_type. |
| 214 | """ |
| 215 | if schema_type == 'string': |
Joe Gregorio | f863f7a | 2011-02-24 03:24:44 -0500 | [diff] [blame] | 216 | if type(value) == type('') or type(value) == type(u''): |
| 217 | return value |
| 218 | else: |
| 219 | return str(value) |
Joe Gregorio | bee8683 | 2011-02-22 10:00:19 -0500 | [diff] [blame] | 220 | elif schema_type == 'integer': |
| 221 | return str(int(value)) |
| 222 | elif schema_type == 'number': |
| 223 | return str(float(value)) |
| 224 | elif schema_type == 'boolean': |
| 225 | return str(bool(value)).lower() |
| 226 | else: |
Joe Gregorio | f863f7a | 2011-02-24 03:24:44 -0500 | [diff] [blame] | 227 | if type(value) == type('') or type(value) == type(u''): |
| 228 | return value |
| 229 | else: |
| 230 | return str(value) |
Joe Gregorio | bee8683 | 2011-02-22 10:00:19 -0500 | [diff] [blame] | 231 | |
Joe Gregorio | fdf7c80 | 2011-06-30 12:33:38 -0400 | [diff] [blame] | 232 | MULTIPLIERS = { |
| 233 | "KB": 2**10, |
| 234 | "MB": 2**20, |
| 235 | "GB": 2**30, |
| 236 | "TB": 2**40, |
| 237 | } |
| 238 | |
| 239 | def _media_size_to_long(maxSize): |
| 240 | """Convert a string media size, such as 10GB or 3TB into an integer.""" |
| 241 | units = maxSize[-2:].upper() |
| 242 | multiplier = MULTIPLIERS.get(units, 0) |
| 243 | if multiplier: |
| 244 | return int(maxSize[:-2])*multiplier |
| 245 | else: |
| 246 | return int(maxSize) |
| 247 | |
Joe Gregorio | bee8683 | 2011-02-22 10:00:19 -0500 | [diff] [blame] | 248 | |
Joe Gregorio | 7a6df3a | 2011-01-31 21:55:21 -0500 | [diff] [blame] | 249 | def createResource(http, baseUrl, model, requestBuilder, |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 250 | developerKey, resourceDesc, futureDesc): |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 251 | |
| 252 | class Resource(object): |
| 253 | """A class for interacting with a resource.""" |
| 254 | |
| 255 | def __init__(self): |
| 256 | self._http = http |
| 257 | self._baseUrl = baseUrl |
| 258 | self._model = model |
Joe Gregorio | 00cf1d9 | 2010-09-27 09:22:03 -0400 | [diff] [blame] | 259 | self._developerKey = developerKey |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 260 | self._requestBuilder = requestBuilder |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 261 | |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 262 | def createMethod(theclass, methodName, methodDesc, futureDesc): |
Joe Gregorio | 6a63a76 | 2011-05-02 22:36:05 -0400 | [diff] [blame] | 263 | pathUrl = methodDesc['path'] |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 264 | httpMethod = methodDesc['httpMethod'] |
Joe Gregorio | 6a63a76 | 2011-05-02 22:36:05 -0400 | [diff] [blame] | 265 | methodId = methodDesc['id'] |
Joe Gregorio | 21f1167 | 2010-08-18 17:23:17 -0400 | [diff] [blame] | 266 | |
Joe Gregorio | fdf7c80 | 2011-06-30 12:33:38 -0400 | [diff] [blame] | 267 | mediaPathUrl = None |
| 268 | accept = [] |
| 269 | maxSize = 0 |
| 270 | if 'mediaUpload' in methodDesc: |
| 271 | mediaUpload = methodDesc['mediaUpload'] |
| 272 | mediaPathUrl = mediaUpload['protocols']['simple']['path'] |
| 273 | accept = mediaUpload['accept'] |
| 274 | maxSize = _media_size_to_long(mediaUpload['maxSize']) |
| 275 | |
Joe Gregorio | ca876e4 | 2011-02-22 19:39:42 -0500 | [diff] [blame] | 276 | if 'parameters' not in methodDesc: |
| 277 | methodDesc['parameters'] = {} |
| 278 | for name in STACK_QUERY_PARAMETERS: |
| 279 | methodDesc['parameters'][name] = { |
| 280 | 'type': 'string', |
Joe Gregorio | 6a63a76 | 2011-05-02 22:36:05 -0400 | [diff] [blame] | 281 | 'location': 'query' |
Joe Gregorio | ca876e4 | 2011-02-22 19:39:42 -0500 | [diff] [blame] | 282 | } |
| 283 | |
Joe Gregorio | f415342 | 2011-03-18 22:45:18 -0400 | [diff] [blame] | 284 | if httpMethod in ['PUT', 'POST', 'PATCH']: |
Joe Gregorio | c3fae8a | 2011-02-18 14:19:50 -0500 | [diff] [blame] | 285 | methodDesc['parameters']['body'] = { |
| 286 | 'description': 'The request body.', |
Joe Gregorio | c2a7393 | 2011-02-22 10:17:06 -0500 | [diff] [blame] | 287 | 'type': 'object', |
Joe Gregorio | 1ae3e74 | 2011-02-25 15:17:14 -0500 | [diff] [blame] | 288 | 'required': True, |
Joe Gregorio | c3fae8a | 2011-02-18 14:19:50 -0500 | [diff] [blame] | 289 | } |
Joe Gregorio | fdf7c80 | 2011-06-30 12:33:38 -0400 | [diff] [blame] | 290 | if 'mediaUpload' in methodDesc: |
| 291 | methodDesc['parameters']['media_body'] = { |
| 292 | 'description': 'The filename of the media request body.', |
| 293 | 'type': 'string', |
| 294 | 'required': False, |
| 295 | } |
| 296 | methodDesc['parameters']['body']['required'] = False |
ade@google.com | 850cf55 | 2010-08-20 23:24:56 +0100 | [diff] [blame] | 297 | |
Joe Gregorio | ca876e4 | 2011-02-22 19:39:42 -0500 | [diff] [blame] | 298 | argmap = {} # Map from method parameter name to query parameter name |
ade@google.com | 850cf55 | 2010-08-20 23:24:56 +0100 | [diff] [blame] | 299 | required_params = [] # Required parameters |
Joe Gregorio | 61d7e96 | 2011-02-22 22:52:07 -0500 | [diff] [blame] | 300 | repeated_params = [] # Repeated parameters |
ade@google.com | 850cf55 | 2010-08-20 23:24:56 +0100 | [diff] [blame] | 301 | pattern_params = {} # Parameters that must match a regex |
| 302 | query_params = [] # Parameters that will be used in the query string |
| 303 | path_params = {} # Parameters that will be used in the base URL |
Joe Gregorio | bee8683 | 2011-02-22 10:00:19 -0500 | [diff] [blame] | 304 | param_type = {} # The type of the parameter |
Joe Gregorio | ca876e4 | 2011-02-22 19:39:42 -0500 | [diff] [blame] | 305 | enum_params = {} # Allowable enumeration values for each parameter |
| 306 | |
| 307 | |
Joe Gregorio | 4292c6e | 2010-09-09 14:32:43 -0400 | [diff] [blame] | 308 | if 'parameters' in methodDesc: |
| 309 | for arg, desc in methodDesc['parameters'].iteritems(): |
| 310 | param = key2param(arg) |
| 311 | argmap[param] = arg |
Joe Gregorio | 21f1167 | 2010-08-18 17:23:17 -0400 | [diff] [blame] | 312 | |
Joe Gregorio | 4292c6e | 2010-09-09 14:32:43 -0400 | [diff] [blame] | 313 | if desc.get('pattern', ''): |
| 314 | pattern_params[param] = desc['pattern'] |
Joe Gregorio | bee8683 | 2011-02-22 10:00:19 -0500 | [diff] [blame] | 315 | if desc.get('enum', ''): |
| 316 | enum_params[param] = desc['enum'] |
Joe Gregorio | 4292c6e | 2010-09-09 14:32:43 -0400 | [diff] [blame] | 317 | if desc.get('required', False): |
| 318 | required_params.append(param) |
Joe Gregorio | 61d7e96 | 2011-02-22 22:52:07 -0500 | [diff] [blame] | 319 | if desc.get('repeated', False): |
| 320 | repeated_params.append(param) |
Joe Gregorio | 6a63a76 | 2011-05-02 22:36:05 -0400 | [diff] [blame] | 321 | if desc.get('location') == 'query': |
Joe Gregorio | 4292c6e | 2010-09-09 14:32:43 -0400 | [diff] [blame] | 322 | query_params.append(param) |
Joe Gregorio | 6a63a76 | 2011-05-02 22:36:05 -0400 | [diff] [blame] | 323 | if desc.get('location') == 'path': |
Joe Gregorio | 4292c6e | 2010-09-09 14:32:43 -0400 | [diff] [blame] | 324 | path_params[param] = param |
Joe Gregorio | bee8683 | 2011-02-22 10:00:19 -0500 | [diff] [blame] | 325 | param_type[param] = desc.get('type', 'string') |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 326 | |
Joe Gregorio | bc2ff9b | 2010-11-08 09:20:48 -0500 | [diff] [blame] | 327 | for match in URITEMPLATE.finditer(pathUrl): |
| 328 | for namematch in VARNAME.finditer(match.group(0)): |
| 329 | name = key2param(namematch.group(0)) |
| 330 | path_params[name] = name |
| 331 | if name in query_params: |
| 332 | query_params.remove(name) |
| 333 | |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 334 | def method(self, **kwargs): |
| 335 | for name in kwargs.iterkeys(): |
Joe Gregorio | ca876e4 | 2011-02-22 19:39:42 -0500 | [diff] [blame] | 336 | if name not in argmap: |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 337 | raise TypeError('Got an unexpected keyword argument "%s"' % name) |
Joe Gregorio | 21f1167 | 2010-08-18 17:23:17 -0400 | [diff] [blame] | 338 | |
ade@google.com | 850cf55 | 2010-08-20 23:24:56 +0100 | [diff] [blame] | 339 | for name in required_params: |
Joe Gregorio | fbf9d0d | 2010-08-18 16:50:47 -0400 | [diff] [blame] | 340 | if name not in kwargs: |
| 341 | raise TypeError('Missing required parameter "%s"' % name) |
Joe Gregorio | 21f1167 | 2010-08-18 17:23:17 -0400 | [diff] [blame] | 342 | |
ade@google.com | 850cf55 | 2010-08-20 23:24:56 +0100 | [diff] [blame] | 343 | for name, regex in pattern_params.iteritems(): |
Joe Gregorio | 21f1167 | 2010-08-18 17:23:17 -0400 | [diff] [blame] | 344 | if name in kwargs: |
| 345 | if re.match(regex, kwargs[name]) is None: |
Joe Gregorio | 3bbbf66 | 2010-08-30 16:41:53 -0400 | [diff] [blame] | 346 | raise TypeError( |
| 347 | 'Parameter "%s" value "%s" does not match the pattern "%s"' % |
| 348 | (name, kwargs[name], regex)) |
Joe Gregorio | 21f1167 | 2010-08-18 17:23:17 -0400 | [diff] [blame] | 349 | |
Joe Gregorio | bee8683 | 2011-02-22 10:00:19 -0500 | [diff] [blame] | 350 | for name, enums in enum_params.iteritems(): |
| 351 | if name in kwargs: |
| 352 | if kwargs[name] not in enums: |
| 353 | raise TypeError( |
Joe Gregorio | ca876e4 | 2011-02-22 19:39:42 -0500 | [diff] [blame] | 354 | 'Parameter "%s" value "%s" is not an allowed value in "%s"' % |
Joe Gregorio | bee8683 | 2011-02-22 10:00:19 -0500 | [diff] [blame] | 355 | (name, kwargs[name], str(enums))) |
| 356 | |
ade@google.com | 850cf55 | 2010-08-20 23:24:56 +0100 | [diff] [blame] | 357 | actual_query_params = {} |
| 358 | actual_path_params = {} |
Joe Gregorio | 21f1167 | 2010-08-18 17:23:17 -0400 | [diff] [blame] | 359 | for key, value in kwargs.iteritems(): |
Joe Gregorio | 61d7e96 | 2011-02-22 22:52:07 -0500 | [diff] [blame] | 360 | to_type = param_type.get(key, 'string') |
| 361 | # For repeated parameters we cast each member of the list. |
| 362 | if key in repeated_params and type(value) == type([]): |
| 363 | cast_value = [_cast(x, to_type) for x in value] |
| 364 | else: |
| 365 | cast_value = _cast(value, to_type) |
ade@google.com | 850cf55 | 2010-08-20 23:24:56 +0100 | [diff] [blame] | 366 | if key in query_params: |
Joe Gregorio | 61d7e96 | 2011-02-22 22:52:07 -0500 | [diff] [blame] | 367 | actual_query_params[argmap[key]] = cast_value |
ade@google.com | 850cf55 | 2010-08-20 23:24:56 +0100 | [diff] [blame] | 368 | if key in path_params: |
Joe Gregorio | 61d7e96 | 2011-02-22 22:52:07 -0500 | [diff] [blame] | 369 | actual_path_params[argmap[key]] = cast_value |
ade@google.com | 850cf55 | 2010-08-20 23:24:56 +0100 | [diff] [blame] | 370 | body_value = kwargs.get('body', None) |
Joe Gregorio | fdf7c80 | 2011-06-30 12:33:38 -0400 | [diff] [blame] | 371 | media_filename = kwargs.get('media_body', None) |
Joe Gregorio | 21f1167 | 2010-08-18 17:23:17 -0400 | [diff] [blame] | 372 | |
Joe Gregorio | 00cf1d9 | 2010-09-27 09:22:03 -0400 | [diff] [blame] | 373 | if self._developerKey: |
| 374 | actual_query_params['key'] = self._developerKey |
| 375 | |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 376 | headers = {} |
Joe Gregorio | 3bbbf66 | 2010-08-30 16:41:53 -0400 | [diff] [blame] | 377 | headers, params, query, body = self._model.request(headers, |
| 378 | actual_path_params, actual_query_params, body_value) |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 379 | |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 380 | expanded_url = uritemplate.expand(pathUrl, params) |
Joe Gregorio | 922b78c | 2011-05-26 21:36:34 -0400 | [diff] [blame] | 381 | url = urlparse.urljoin(self._baseUrl, expanded_url + query) |
| 382 | |
| 383 | if media_filename: |
| 384 | (media_mime_type, encoding) = mimetypes.guess_type(media_filename) |
| 385 | if media_mime_type is None: |
| 386 | raise UnknownFileType(media_filename) |
Joe Gregorio | fdf7c80 | 2011-06-30 12:33:38 -0400 | [diff] [blame] | 387 | if not mimeparse.best_match([media_mime_type], ','.join(accept)): |
| 388 | raise UnacceptableMimeTypeError(media_mime_type) |
Joe Gregorio | 922b78c | 2011-05-26 21:36:34 -0400 | [diff] [blame] | 389 | |
Joe Gregorio | fdf7c80 | 2011-06-30 12:33:38 -0400 | [diff] [blame] | 390 | # Check the maxSize |
| 391 | if maxSize > 0 and os.path.getsize(media_filename) > maxSize: |
| 392 | raise MediaUploadSizeError(media_filename) |
| 393 | |
| 394 | # Use the media path uri for media uploads |
| 395 | expanded_url = uritemplate.expand(mediaPathUrl, params) |
| 396 | url = urlparse.urljoin(self._baseUrl, expanded_url + query) |
Joe Gregorio | 922b78c | 2011-05-26 21:36:34 -0400 | [diff] [blame] | 397 | |
| 398 | if body is None: |
| 399 | headers['content-type'] = media_mime_type |
| 400 | # make the body the contents of the file |
| 401 | f = file(media_filename, 'rb') |
| 402 | body = f.read() |
| 403 | f.close() |
| 404 | else: |
| 405 | msgRoot = MIMEMultipart('related') |
| 406 | # msgRoot should not write out it's own headers |
| 407 | setattr(msgRoot, '_write_headers', lambda self: None) |
| 408 | |
| 409 | # attach the body as one part |
| 410 | msg = MIMENonMultipart(*headers['content-type'].split('/')) |
| 411 | msg.set_payload(body) |
| 412 | msgRoot.attach(msg) |
| 413 | |
| 414 | # attach the media as the second part |
| 415 | msg = MIMENonMultipart(*media_mime_type.split('/')) |
| 416 | msg['Content-Transfer-Encoding'] = 'binary' |
| 417 | |
| 418 | f = file(media_filename, 'rb') |
| 419 | msg.set_payload(f.read()) |
| 420 | f.close() |
| 421 | msgRoot.attach(msg) |
| 422 | |
| 423 | body = msgRoot.as_string() |
| 424 | |
| 425 | # must appear after the call to as_string() to get the right boundary |
| 426 | headers['content-type'] = ('multipart/related; ' |
| 427 | 'boundary="%s"') % msgRoot.get_boundary() |
Joe Gregorio | fbf9d0d | 2010-08-18 16:50:47 -0400 | [diff] [blame] | 428 | |
ade@google.com | 850cf55 | 2010-08-20 23:24:56 +0100 | [diff] [blame] | 429 | logging.info('URL being requested: %s' % url) |
Joe Gregorio | abda96f | 2011-02-11 20:19:33 -0500 | [diff] [blame] | 430 | return self._requestBuilder(self._http, |
| 431 | self._model.response, |
| 432 | url, |
| 433 | method=httpMethod, |
| 434 | body=body, |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 435 | headers=headers, |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 436 | methodId=methodId) |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 437 | |
Joe Gregorio | c3fae8a | 2011-02-18 14:19:50 -0500 | [diff] [blame] | 438 | docs = [methodDesc.get('description', DEFAULT_METHOD_DOC), '\n\n'] |
| 439 | if len(argmap) > 0: |
Joe Gregorio | 61d7e96 | 2011-02-22 22:52:07 -0500 | [diff] [blame] | 440 | docs.append('Args:\n') |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 441 | for arg in argmap.iterkeys(): |
Joe Gregorio | ca876e4 | 2011-02-22 19:39:42 -0500 | [diff] [blame] | 442 | if arg in STACK_QUERY_PARAMETERS: |
| 443 | continue |
Joe Gregorio | 61d7e96 | 2011-02-22 22:52:07 -0500 | [diff] [blame] | 444 | repeated = '' |
| 445 | if arg in repeated_params: |
| 446 | repeated = ' (repeated)' |
| 447 | required = '' |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 448 | if arg in required_params: |
Joe Gregorio | 61d7e96 | 2011-02-22 22:52:07 -0500 | [diff] [blame] | 449 | required = ' (required)' |
Joe Gregorio | c2a7393 | 2011-02-22 10:17:06 -0500 | [diff] [blame] | 450 | paramdesc = methodDesc['parameters'][argmap[arg]] |
| 451 | paramdoc = paramdesc.get('description', 'A parameter') |
| 452 | paramtype = paramdesc.get('type', 'string') |
Joe Gregorio | 61d7e96 | 2011-02-22 22:52:07 -0500 | [diff] [blame] | 453 | docs.append(' %s: %s, %s%s%s\n' % (arg, paramtype, paramdoc, required, |
| 454 | repeated)) |
Joe Gregorio | c2a7393 | 2011-02-22 10:17:06 -0500 | [diff] [blame] | 455 | enum = paramdesc.get('enum', []) |
| 456 | enumDesc = paramdesc.get('enumDescriptions', []) |
| 457 | if enum and enumDesc: |
| 458 | docs.append(' Allowed values\n') |
| 459 | for (name, desc) in zip(enum, enumDesc): |
| 460 | docs.append(' %s - %s\n' % (name, desc)) |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 461 | |
| 462 | setattr(method, '__doc__', ''.join(docs)) |
| 463 | setattr(theclass, methodName, method) |
| 464 | |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 465 | def createNextMethod(theclass, methodName, methodDesc, futureDesc): |
Joe Gregorio | 6a63a76 | 2011-05-02 22:36:05 -0400 | [diff] [blame] | 466 | methodId = methodDesc['id'] + '.next' |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 467 | |
Joe Gregorio | c3fae8a | 2011-02-18 14:19:50 -0500 | [diff] [blame] | 468 | def methodNext(self, previous): |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 469 | """ |
| 470 | Takes a single argument, 'body', which is the results |
| 471 | from the last call, and returns the next set of items |
| 472 | in the collection. |
| 473 | |
| 474 | Returns None if there are no more items in |
| 475 | the collection. |
| 476 | """ |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 477 | if futureDesc['type'] != 'uri': |
| 478 | raise UnknownLinkType(futureDesc['type']) |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 479 | |
| 480 | try: |
| 481 | p = previous |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 482 | for key in futureDesc['location']: |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 483 | p = p[key] |
| 484 | url = p |
Joe Gregorio | c5c5a37 | 2010-09-22 11:42:32 -0400 | [diff] [blame] | 485 | except (KeyError, TypeError): |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 486 | return None |
| 487 | |
Joe Gregorio | 00cf1d9 | 2010-09-27 09:22:03 -0400 | [diff] [blame] | 488 | if self._developerKey: |
| 489 | parsed = list(urlparse.urlparse(url)) |
ade@google.com | c5eb46f | 2010-09-27 23:35:39 +0100 | [diff] [blame] | 490 | q = parse_qsl(parsed[4]) |
Joe Gregorio | 00cf1d9 | 2010-09-27 09:22:03 -0400 | [diff] [blame] | 491 | q.append(('key', self._developerKey)) |
| 492 | parsed[4] = urllib.urlencode(q) |
| 493 | url = urlparse.urlunparse(parsed) |
| 494 | |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 495 | headers = {} |
| 496 | headers, params, query, body = self._model.request(headers, {}, {}, None) |
| 497 | |
| 498 | logging.info('URL being requested: %s' % url) |
| 499 | resp, content = self._http.request(url, method='GET', headers=headers) |
| 500 | |
Joe Gregorio | abda96f | 2011-02-11 20:19:33 -0500 | [diff] [blame] | 501 | return self._requestBuilder(self._http, |
| 502 | self._model.response, |
| 503 | url, |
| 504 | method='GET', |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 505 | headers=headers, |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 506 | methodId=methodId) |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 507 | |
Joe Gregorio | c3fae8a | 2011-02-18 14:19:50 -0500 | [diff] [blame] | 508 | setattr(theclass, methodName, methodNext) |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 509 | |
| 510 | # Add basic methods to Resource |
Joe Gregorio | 2379ecc | 2010-10-26 10:51:28 -0400 | [diff] [blame] | 511 | if 'methods' in resourceDesc: |
| 512 | for methodName, methodDesc in resourceDesc['methods'].iteritems(): |
| 513 | if futureDesc: |
| 514 | future = futureDesc['methods'].get(methodName, {}) |
| 515 | else: |
| 516 | future = None |
| 517 | createMethod(Resource, methodName, methodDesc, future) |
| 518 | |
| 519 | # Add in nested resources |
| 520 | if 'resources' in resourceDesc: |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 521 | |
Joe Gregorio | c3fae8a | 2011-02-18 14:19:50 -0500 | [diff] [blame] | 522 | def createResourceMethod(theclass, methodName, methodDesc, futureDesc): |
Joe Gregorio | 2379ecc | 2010-10-26 10:51:28 -0400 | [diff] [blame] | 523 | |
Joe Gregorio | c3fae8a | 2011-02-18 14:19:50 -0500 | [diff] [blame] | 524 | def methodResource(self): |
Joe Gregorio | 2379ecc | 2010-10-26 10:51:28 -0400 | [diff] [blame] | 525 | return createResource(self._http, self._baseUrl, self._model, |
Joe Gregorio | 7a6df3a | 2011-01-31 21:55:21 -0500 | [diff] [blame] | 526 | self._requestBuilder, self._developerKey, |
| 527 | methodDesc, futureDesc) |
Joe Gregorio | 2379ecc | 2010-10-26 10:51:28 -0400 | [diff] [blame] | 528 | |
Joe Gregorio | c3fae8a | 2011-02-18 14:19:50 -0500 | [diff] [blame] | 529 | setattr(methodResource, '__doc__', 'A collection resource.') |
| 530 | setattr(methodResource, '__is_resource__', True) |
| 531 | setattr(theclass, methodName, methodResource) |
Joe Gregorio | 2379ecc | 2010-10-26 10:51:28 -0400 | [diff] [blame] | 532 | |
| 533 | for methodName, methodDesc in resourceDesc['resources'].iteritems(): |
| 534 | if futureDesc and 'resources' in futureDesc: |
| 535 | future = futureDesc['resources'].get(methodName, {}) |
| 536 | else: |
| 537 | future = {} |
Joe Gregorio | c3fae8a | 2011-02-18 14:19:50 -0500 | [diff] [blame] | 538 | createResourceMethod(Resource, methodName, methodDesc, future) |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 539 | |
| 540 | # Add <m>_next() methods to Resource |
Joe Gregorio | 7a6df3a | 2011-01-31 21:55:21 -0500 | [diff] [blame] | 541 | if futureDesc and 'methods' in futureDesc: |
Joe Gregorio | 2379ecc | 2010-10-26 10:51:28 -0400 | [diff] [blame] | 542 | for methodName, methodDesc in futureDesc['methods'].iteritems(): |
| 543 | if 'next' in methodDesc and methodName in resourceDesc['methods']: |
Joe Gregorio | 61d7e96 | 2011-02-22 22:52:07 -0500 | [diff] [blame] | 544 | createNextMethod(Resource, methodName + '_next', |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 545 | resourceDesc['methods'][methodName], |
| 546 | methodDesc['next']) |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 547 | |
| 548 | return Resource() |