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