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: |
Joe Gregorio | f863f7a | 2011-02-24 03:24:44 -0500 | [diff] [blame^] | 167 | features = service.get('features', []) |
Joe Gregorio | 266c644 | 2011-02-23 16:08:54 -0500 | [diff] [blame] | 168 | model = JsonModel('dataWrapper' in features) |
Joe Gregorio | 7a6df3a | 2011-01-31 21:55:21 -0500 | [diff] [blame] | 169 | resource = createResource(http, base, model, requestBuilder, developerKey, |
| 170 | service, future) |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 171 | |
Joe Gregorio | 7a6df3a | 2011-01-31 21:55:21 -0500 | [diff] [blame] | 172 | def auth_method(): |
| 173 | """Discovery information about the authentication the API uses.""" |
| 174 | return auth_discovery |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 175 | |
Joe Gregorio | 7a6df3a | 2011-01-31 21:55:21 -0500 | [diff] [blame] | 176 | setattr(resource, 'auth_discovery', auth_method) |
Joe Gregorio | a2f56e7 | 2010-09-09 15:15:56 -0400 | [diff] [blame] | 177 | |
Joe Gregorio | 7a6df3a | 2011-01-31 21:55:21 -0500 | [diff] [blame] | 178 | return resource |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 179 | |
| 180 | |
Joe Gregorio | 61d7e96 | 2011-02-22 22:52:07 -0500 | [diff] [blame] | 181 | def _cast(value, schema_type): |
Joe Gregorio | bee8683 | 2011-02-22 10:00:19 -0500 | [diff] [blame] | 182 | """Convert value to a string based on JSON Schema type. |
| 183 | |
| 184 | See http://tools.ietf.org/html/draft-zyp-json-schema-03 for more details on |
| 185 | JSON Schema. |
| 186 | |
| 187 | Args: |
| 188 | value: any, the value to convert |
| 189 | schema_type: string, the type that value should be interpreted as |
| 190 | |
| 191 | Returns: |
| 192 | A string representation of 'value' based on the schema_type. |
| 193 | """ |
| 194 | if schema_type == 'string': |
Joe Gregorio | f863f7a | 2011-02-24 03:24:44 -0500 | [diff] [blame^] | 195 | if type(value) == type('') or type(value) == type(u''): |
| 196 | return value |
| 197 | else: |
| 198 | return str(value) |
Joe Gregorio | bee8683 | 2011-02-22 10:00:19 -0500 | [diff] [blame] | 199 | elif schema_type == 'integer': |
| 200 | return str(int(value)) |
| 201 | elif schema_type == 'number': |
| 202 | return str(float(value)) |
| 203 | elif schema_type == 'boolean': |
| 204 | return str(bool(value)).lower() |
| 205 | else: |
Joe Gregorio | f863f7a | 2011-02-24 03:24:44 -0500 | [diff] [blame^] | 206 | if type(value) == type('') or type(value) == type(u''): |
| 207 | return value |
| 208 | else: |
| 209 | return str(value) |
Joe Gregorio | bee8683 | 2011-02-22 10:00:19 -0500 | [diff] [blame] | 210 | |
| 211 | |
Joe Gregorio | 7a6df3a | 2011-01-31 21:55:21 -0500 | [diff] [blame] | 212 | def createResource(http, baseUrl, model, requestBuilder, |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 213 | developerKey, resourceDesc, futureDesc): |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 214 | |
| 215 | class Resource(object): |
| 216 | """A class for interacting with a resource.""" |
| 217 | |
| 218 | def __init__(self): |
| 219 | self._http = http |
| 220 | self._baseUrl = baseUrl |
| 221 | self._model = model |
Joe Gregorio | 00cf1d9 | 2010-09-27 09:22:03 -0400 | [diff] [blame] | 222 | self._developerKey = developerKey |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 223 | self._requestBuilder = requestBuilder |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 224 | |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 225 | def createMethod(theclass, methodName, methodDesc, futureDesc): |
Joe Gregorio | 2379ecc | 2010-10-26 10:51:28 -0400 | [diff] [blame] | 226 | pathUrl = methodDesc['restPath'] |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 227 | httpMethod = methodDesc['httpMethod'] |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 228 | methodId = methodDesc['rpcMethod'] |
Joe Gregorio | 21f1167 | 2010-08-18 17:23:17 -0400 | [diff] [blame] | 229 | |
Joe Gregorio | ca876e4 | 2011-02-22 19:39:42 -0500 | [diff] [blame] | 230 | if 'parameters' not in methodDesc: |
| 231 | methodDesc['parameters'] = {} |
| 232 | for name in STACK_QUERY_PARAMETERS: |
| 233 | methodDesc['parameters'][name] = { |
| 234 | 'type': 'string', |
| 235 | 'restParameterType': 'query' |
| 236 | } |
| 237 | |
ade@google.com | 850cf55 | 2010-08-20 23:24:56 +0100 | [diff] [blame] | 238 | if httpMethod in ['PUT', 'POST']: |
Joe Gregorio | c3fae8a | 2011-02-18 14:19:50 -0500 | [diff] [blame] | 239 | methodDesc['parameters']['body'] = { |
| 240 | 'description': 'The request body.', |
Joe Gregorio | c2a7393 | 2011-02-22 10:17:06 -0500 | [diff] [blame] | 241 | 'type': 'object', |
Joe Gregorio | c3fae8a | 2011-02-18 14:19:50 -0500 | [diff] [blame] | 242 | } |
ade@google.com | 850cf55 | 2010-08-20 23:24:56 +0100 | [diff] [blame] | 243 | |
Joe Gregorio | ca876e4 | 2011-02-22 19:39:42 -0500 | [diff] [blame] | 244 | argmap = {} # Map from method parameter name to query parameter name |
ade@google.com | 850cf55 | 2010-08-20 23:24:56 +0100 | [diff] [blame] | 245 | required_params = [] # Required parameters |
Joe Gregorio | 61d7e96 | 2011-02-22 22:52:07 -0500 | [diff] [blame] | 246 | repeated_params = [] # Repeated parameters |
ade@google.com | 850cf55 | 2010-08-20 23:24:56 +0100 | [diff] [blame] | 247 | pattern_params = {} # Parameters that must match a regex |
| 248 | query_params = [] # Parameters that will be used in the query string |
| 249 | path_params = {} # Parameters that will be used in the base URL |
Joe Gregorio | bee8683 | 2011-02-22 10:00:19 -0500 | [diff] [blame] | 250 | param_type = {} # The type of the parameter |
Joe Gregorio | ca876e4 | 2011-02-22 19:39:42 -0500 | [diff] [blame] | 251 | enum_params = {} # Allowable enumeration values for each parameter |
| 252 | |
| 253 | |
Joe Gregorio | 4292c6e | 2010-09-09 14:32:43 -0400 | [diff] [blame] | 254 | if 'parameters' in methodDesc: |
| 255 | for arg, desc in methodDesc['parameters'].iteritems(): |
| 256 | param = key2param(arg) |
| 257 | argmap[param] = arg |
Joe Gregorio | 21f1167 | 2010-08-18 17:23:17 -0400 | [diff] [blame] | 258 | |
Joe Gregorio | 4292c6e | 2010-09-09 14:32:43 -0400 | [diff] [blame] | 259 | if desc.get('pattern', ''): |
| 260 | pattern_params[param] = desc['pattern'] |
Joe Gregorio | bee8683 | 2011-02-22 10:00:19 -0500 | [diff] [blame] | 261 | if desc.get('enum', ''): |
| 262 | enum_params[param] = desc['enum'] |
Joe Gregorio | 4292c6e | 2010-09-09 14:32:43 -0400 | [diff] [blame] | 263 | if desc.get('required', False): |
| 264 | required_params.append(param) |
Joe Gregorio | 61d7e96 | 2011-02-22 22:52:07 -0500 | [diff] [blame] | 265 | if desc.get('repeated', False): |
| 266 | repeated_params.append(param) |
Joe Gregorio | 2379ecc | 2010-10-26 10:51:28 -0400 | [diff] [blame] | 267 | if desc.get('restParameterType') == 'query': |
Joe Gregorio | 4292c6e | 2010-09-09 14:32:43 -0400 | [diff] [blame] | 268 | query_params.append(param) |
Joe Gregorio | 2379ecc | 2010-10-26 10:51:28 -0400 | [diff] [blame] | 269 | if desc.get('restParameterType') == 'path': |
Joe Gregorio | 4292c6e | 2010-09-09 14:32:43 -0400 | [diff] [blame] | 270 | path_params[param] = param |
Joe Gregorio | bee8683 | 2011-02-22 10:00:19 -0500 | [diff] [blame] | 271 | param_type[param] = desc.get('type', 'string') |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 272 | |
Joe Gregorio | bc2ff9b | 2010-11-08 09:20:48 -0500 | [diff] [blame] | 273 | for match in URITEMPLATE.finditer(pathUrl): |
| 274 | for namematch in VARNAME.finditer(match.group(0)): |
| 275 | name = key2param(namematch.group(0)) |
| 276 | path_params[name] = name |
| 277 | if name in query_params: |
| 278 | query_params.remove(name) |
| 279 | |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 280 | def method(self, **kwargs): |
| 281 | for name in kwargs.iterkeys(): |
Joe Gregorio | ca876e4 | 2011-02-22 19:39:42 -0500 | [diff] [blame] | 282 | if name not in argmap: |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 283 | raise TypeError('Got an unexpected keyword argument "%s"' % name) |
Joe Gregorio | 21f1167 | 2010-08-18 17:23:17 -0400 | [diff] [blame] | 284 | |
ade@google.com | 850cf55 | 2010-08-20 23:24:56 +0100 | [diff] [blame] | 285 | for name in required_params: |
Joe Gregorio | fbf9d0d | 2010-08-18 16:50:47 -0400 | [diff] [blame] | 286 | if name not in kwargs: |
| 287 | raise TypeError('Missing required parameter "%s"' % name) |
Joe Gregorio | 21f1167 | 2010-08-18 17:23:17 -0400 | [diff] [blame] | 288 | |
ade@google.com | 850cf55 | 2010-08-20 23:24:56 +0100 | [diff] [blame] | 289 | for name, regex in pattern_params.iteritems(): |
Joe Gregorio | 21f1167 | 2010-08-18 17:23:17 -0400 | [diff] [blame] | 290 | if name in kwargs: |
| 291 | if re.match(regex, kwargs[name]) is None: |
Joe Gregorio | 3bbbf66 | 2010-08-30 16:41:53 -0400 | [diff] [blame] | 292 | raise TypeError( |
| 293 | 'Parameter "%s" value "%s" does not match the pattern "%s"' % |
| 294 | (name, kwargs[name], regex)) |
Joe Gregorio | 21f1167 | 2010-08-18 17:23:17 -0400 | [diff] [blame] | 295 | |
Joe Gregorio | bee8683 | 2011-02-22 10:00:19 -0500 | [diff] [blame] | 296 | for name, enums in enum_params.iteritems(): |
| 297 | if name in kwargs: |
| 298 | if kwargs[name] not in enums: |
| 299 | raise TypeError( |
Joe Gregorio | ca876e4 | 2011-02-22 19:39:42 -0500 | [diff] [blame] | 300 | 'Parameter "%s" value "%s" is not an allowed value in "%s"' % |
Joe Gregorio | bee8683 | 2011-02-22 10:00:19 -0500 | [diff] [blame] | 301 | (name, kwargs[name], str(enums))) |
| 302 | |
ade@google.com | 850cf55 | 2010-08-20 23:24:56 +0100 | [diff] [blame] | 303 | actual_query_params = {} |
| 304 | actual_path_params = {} |
Joe Gregorio | 21f1167 | 2010-08-18 17:23:17 -0400 | [diff] [blame] | 305 | for key, value in kwargs.iteritems(): |
Joe Gregorio | 61d7e96 | 2011-02-22 22:52:07 -0500 | [diff] [blame] | 306 | to_type = param_type.get(key, 'string') |
| 307 | # For repeated parameters we cast each member of the list. |
| 308 | if key in repeated_params and type(value) == type([]): |
| 309 | cast_value = [_cast(x, to_type) for x in value] |
| 310 | else: |
| 311 | cast_value = _cast(value, to_type) |
ade@google.com | 850cf55 | 2010-08-20 23:24:56 +0100 | [diff] [blame] | 312 | if key in query_params: |
Joe Gregorio | 61d7e96 | 2011-02-22 22:52:07 -0500 | [diff] [blame] | 313 | actual_query_params[argmap[key]] = cast_value |
ade@google.com | 850cf55 | 2010-08-20 23:24:56 +0100 | [diff] [blame] | 314 | if key in path_params: |
Joe Gregorio | 61d7e96 | 2011-02-22 22:52:07 -0500 | [diff] [blame] | 315 | actual_path_params[argmap[key]] = cast_value |
ade@google.com | 850cf55 | 2010-08-20 23:24:56 +0100 | [diff] [blame] | 316 | body_value = kwargs.get('body', None) |
Joe Gregorio | 21f1167 | 2010-08-18 17:23:17 -0400 | [diff] [blame] | 317 | |
Joe Gregorio | 00cf1d9 | 2010-09-27 09:22:03 -0400 | [diff] [blame] | 318 | if self._developerKey: |
| 319 | actual_query_params['key'] = self._developerKey |
| 320 | |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 321 | headers = {} |
Joe Gregorio | 3bbbf66 | 2010-08-30 16:41:53 -0400 | [diff] [blame] | 322 | headers, params, query, body = self._model.request(headers, |
| 323 | actual_path_params, actual_query_params, body_value) |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 324 | |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 325 | # TODO(ade) This exists to fix a bug in V1 of the Buzz discovery |
| 326 | # document. Base URLs should not contain any path elements. If they do |
| 327 | # then urlparse.urljoin will strip them out This results in an incorrect |
| 328 | # URL which returns a 404 |
ade@google.com | 7ebb2ca | 2010-09-29 16:42:15 +0100 | [diff] [blame] | 329 | url_result = urlparse.urlsplit(self._baseUrl) |
| 330 | new_base_url = url_result.scheme + '://' + url_result.netloc |
| 331 | |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 332 | expanded_url = uritemplate.expand(pathUrl, params) |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 333 | url = urlparse.urljoin(new_base_url, |
| 334 | url_result.path + expanded_url + query) |
Joe Gregorio | fbf9d0d | 2010-08-18 16:50:47 -0400 | [diff] [blame] | 335 | |
ade@google.com | 850cf55 | 2010-08-20 23:24:56 +0100 | [diff] [blame] | 336 | logging.info('URL being requested: %s' % url) |
Joe Gregorio | abda96f | 2011-02-11 20:19:33 -0500 | [diff] [blame] | 337 | return self._requestBuilder(self._http, |
| 338 | self._model.response, |
| 339 | url, |
| 340 | method=httpMethod, |
| 341 | body=body, |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 342 | headers=headers, |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 343 | methodId=methodId) |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 344 | |
Joe Gregorio | c3fae8a | 2011-02-18 14:19:50 -0500 | [diff] [blame] | 345 | docs = [methodDesc.get('description', DEFAULT_METHOD_DOC), '\n\n'] |
| 346 | if len(argmap) > 0: |
Joe Gregorio | 61d7e96 | 2011-02-22 22:52:07 -0500 | [diff] [blame] | 347 | docs.append('Args:\n') |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 348 | for arg in argmap.iterkeys(): |
Joe Gregorio | ca876e4 | 2011-02-22 19:39:42 -0500 | [diff] [blame] | 349 | if arg in STACK_QUERY_PARAMETERS: |
| 350 | continue |
Joe Gregorio | 61d7e96 | 2011-02-22 22:52:07 -0500 | [diff] [blame] | 351 | repeated = '' |
| 352 | if arg in repeated_params: |
| 353 | repeated = ' (repeated)' |
| 354 | required = '' |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 355 | if arg in required_params: |
Joe Gregorio | 61d7e96 | 2011-02-22 22:52:07 -0500 | [diff] [blame] | 356 | required = ' (required)' |
Joe Gregorio | c2a7393 | 2011-02-22 10:17:06 -0500 | [diff] [blame] | 357 | paramdesc = methodDesc['parameters'][argmap[arg]] |
| 358 | paramdoc = paramdesc.get('description', 'A parameter') |
| 359 | paramtype = paramdesc.get('type', 'string') |
Joe Gregorio | 61d7e96 | 2011-02-22 22:52:07 -0500 | [diff] [blame] | 360 | docs.append(' %s: %s, %s%s%s\n' % (arg, paramtype, paramdoc, required, |
| 361 | repeated)) |
Joe Gregorio | c2a7393 | 2011-02-22 10:17:06 -0500 | [diff] [blame] | 362 | enum = paramdesc.get('enum', []) |
| 363 | enumDesc = paramdesc.get('enumDescriptions', []) |
| 364 | if enum and enumDesc: |
| 365 | docs.append(' Allowed values\n') |
| 366 | for (name, desc) in zip(enum, enumDesc): |
| 367 | docs.append(' %s - %s\n' % (name, desc)) |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 368 | |
| 369 | setattr(method, '__doc__', ''.join(docs)) |
| 370 | setattr(theclass, methodName, method) |
| 371 | |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 372 | def createNextMethod(theclass, methodName, methodDesc, futureDesc): |
| 373 | methodId = methodDesc['rpcMethod'] + '.next' |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 374 | |
Joe Gregorio | c3fae8a | 2011-02-18 14:19:50 -0500 | [diff] [blame] | 375 | def methodNext(self, previous): |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 376 | """ |
| 377 | Takes a single argument, 'body', which is the results |
| 378 | from the last call, and returns the next set of items |
| 379 | in the collection. |
| 380 | |
| 381 | Returns None if there are no more items in |
| 382 | the collection. |
| 383 | """ |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 384 | if futureDesc['type'] != 'uri': |
| 385 | raise UnknownLinkType(futureDesc['type']) |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 386 | |
| 387 | try: |
| 388 | p = previous |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 389 | for key in futureDesc['location']: |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 390 | p = p[key] |
| 391 | url = p |
Joe Gregorio | c5c5a37 | 2010-09-22 11:42:32 -0400 | [diff] [blame] | 392 | except (KeyError, TypeError): |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 393 | return None |
| 394 | |
Joe Gregorio | 00cf1d9 | 2010-09-27 09:22:03 -0400 | [diff] [blame] | 395 | if self._developerKey: |
| 396 | parsed = list(urlparse.urlparse(url)) |
ade@google.com | c5eb46f | 2010-09-27 23:35:39 +0100 | [diff] [blame] | 397 | q = parse_qsl(parsed[4]) |
Joe Gregorio | 00cf1d9 | 2010-09-27 09:22:03 -0400 | [diff] [blame] | 398 | q.append(('key', self._developerKey)) |
| 399 | parsed[4] = urllib.urlencode(q) |
| 400 | url = urlparse.urlunparse(parsed) |
| 401 | |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 402 | headers = {} |
| 403 | headers, params, query, body = self._model.request(headers, {}, {}, None) |
| 404 | |
| 405 | logging.info('URL being requested: %s' % url) |
| 406 | resp, content = self._http.request(url, method='GET', headers=headers) |
| 407 | |
Joe Gregorio | abda96f | 2011-02-11 20:19:33 -0500 | [diff] [blame] | 408 | return self._requestBuilder(self._http, |
| 409 | self._model.response, |
| 410 | url, |
| 411 | method='GET', |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 412 | headers=headers, |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 413 | methodId=methodId) |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 414 | |
Joe Gregorio | c3fae8a | 2011-02-18 14:19:50 -0500 | [diff] [blame] | 415 | setattr(theclass, methodName, methodNext) |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 416 | |
| 417 | # Add basic methods to Resource |
Joe Gregorio | 2379ecc | 2010-10-26 10:51:28 -0400 | [diff] [blame] | 418 | if 'methods' in resourceDesc: |
| 419 | for methodName, methodDesc in resourceDesc['methods'].iteritems(): |
| 420 | if futureDesc: |
| 421 | future = futureDesc['methods'].get(methodName, {}) |
| 422 | else: |
| 423 | future = None |
| 424 | createMethod(Resource, methodName, methodDesc, future) |
| 425 | |
| 426 | # Add in nested resources |
| 427 | if 'resources' in resourceDesc: |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 428 | |
Joe Gregorio | c3fae8a | 2011-02-18 14:19:50 -0500 | [diff] [blame] | 429 | def createResourceMethod(theclass, methodName, methodDesc, futureDesc): |
Joe Gregorio | 2379ecc | 2010-10-26 10:51:28 -0400 | [diff] [blame] | 430 | |
Joe Gregorio | c3fae8a | 2011-02-18 14:19:50 -0500 | [diff] [blame] | 431 | def methodResource(self): |
Joe Gregorio | 2379ecc | 2010-10-26 10:51:28 -0400 | [diff] [blame] | 432 | return createResource(self._http, self._baseUrl, self._model, |
Joe Gregorio | 7a6df3a | 2011-01-31 21:55:21 -0500 | [diff] [blame] | 433 | self._requestBuilder, self._developerKey, |
| 434 | methodDesc, futureDesc) |
Joe Gregorio | 2379ecc | 2010-10-26 10:51:28 -0400 | [diff] [blame] | 435 | |
Joe Gregorio | c3fae8a | 2011-02-18 14:19:50 -0500 | [diff] [blame] | 436 | setattr(methodResource, '__doc__', 'A collection resource.') |
| 437 | setattr(methodResource, '__is_resource__', True) |
| 438 | setattr(theclass, methodName, methodResource) |
Joe Gregorio | 2379ecc | 2010-10-26 10:51:28 -0400 | [diff] [blame] | 439 | |
| 440 | for methodName, methodDesc in resourceDesc['resources'].iteritems(): |
| 441 | if futureDesc and 'resources' in futureDesc: |
| 442 | future = futureDesc['resources'].get(methodName, {}) |
| 443 | else: |
| 444 | future = {} |
Joe Gregorio | c3fae8a | 2011-02-18 14:19:50 -0500 | [diff] [blame] | 445 | createResourceMethod(Resource, methodName, methodDesc, future) |
Joe Gregorio | 6d5e94f | 2010-08-25 23:49:30 -0400 | [diff] [blame] | 446 | |
| 447 | # Add <m>_next() methods to Resource |
Joe Gregorio | 7a6df3a | 2011-01-31 21:55:21 -0500 | [diff] [blame] | 448 | if futureDesc and 'methods' in futureDesc: |
Joe Gregorio | 2379ecc | 2010-10-26 10:51:28 -0400 | [diff] [blame] | 449 | for methodName, methodDesc in futureDesc['methods'].iteritems(): |
| 450 | if 'next' in methodDesc and methodName in resourceDesc['methods']: |
Joe Gregorio | 61d7e96 | 2011-02-22 22:52:07 -0500 | [diff] [blame] | 451 | createNextMethod(Resource, methodName + '_next', |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 452 | resourceDesc['methods'][methodName], |
| 453 | methodDesc['next']) |
Joe Gregorio | 48d361f | 2010-08-18 13:19:21 -0400 | [diff] [blame] | 454 | |
| 455 | return Resource() |