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