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