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