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