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