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