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