Joe Gregorio | 88f699f | 2012-06-07 13:36:06 -0400 | [diff] [blame] | 1 | # Copyright (C) 2012 Google Inc. |
Joe Gregorio | 20a5aa9 | 2011-04-01 17:44:25 -0400 | [diff] [blame] | 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. |
Joe Gregorio | c5c5a37 | 2010-09-22 11:42:32 -0400 | [diff] [blame] | 14 | |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 15 | """Classes to encapsulate a single HTTP request. |
Joe Gregorio | c5c5a37 | 2010-09-22 11:42:32 -0400 | [diff] [blame] | 16 | |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 17 | The classes implement a command pattern, with every |
| 18 | object supporting an execute() method that does the |
| 19 | actuall HTTP request. |
Joe Gregorio | c5c5a37 | 2010-09-22 11:42:32 -0400 | [diff] [blame] | 20 | """ |
| 21 | |
| 22 | __author__ = 'jcgregorio@google.com (Joe Gregorio)' |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 23 | |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 24 | import StringIO |
Ali Afshar | 6f11ea1 | 2012-02-07 10:32:14 -0500 | [diff] [blame] | 25 | import base64 |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 26 | import copy |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 27 | import gzip |
Joe Gregorio | c672246 | 2010-12-20 14:29:28 -0500 | [diff] [blame] | 28 | import httplib2 |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 29 | import mimeparse |
| 30 | import mimetypes |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 31 | import os |
| 32 | import urllib |
| 33 | import urlparse |
| 34 | import uuid |
Joe Gregorio | cb8103d | 2011-02-11 23:20:52 -0500 | [diff] [blame] | 35 | |
Joe Gregorio | 654f4a2 | 2012-02-09 14:15:44 -0500 | [diff] [blame] | 36 | from email.generator import Generator |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 37 | from email.mime.multipart import MIMEMultipart |
| 38 | from email.mime.nonmultipart import MIMENonMultipart |
| 39 | from email.parser import FeedParser |
| 40 | from errors import BatchError |
Joe Gregorio | 4939655 | 2011-03-08 10:39:00 -0500 | [diff] [blame] | 41 | from errors import HttpError |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 42 | from errors import ResumableUploadError |
Joe Gregorio | a388ce3 | 2011-09-09 17:19:13 -0400 | [diff] [blame] | 43 | from errors import UnexpectedBodyError |
| 44 | from errors import UnexpectedMethodError |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 45 | from model import JsonModel |
Joe Gregorio | 549230c | 2012-01-11 10:38:05 -0500 | [diff] [blame] | 46 | from oauth2client.anyjson import simplejson |
Joe Gregorio | c5c5a37 | 2010-09-22 11:42:32 -0400 | [diff] [blame] | 47 | |
| 48 | |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 49 | DEFAULT_CHUNK_SIZE = 512*1024 |
| 50 | |
Joe Gregorio | ba5c790 | 2012-08-03 12:48:16 -0400 | [diff] [blame^] | 51 | MAX_URI_LENGTH = 4000 |
| 52 | |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 53 | |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 54 | class MediaUploadProgress(object): |
| 55 | """Status of a resumable upload.""" |
| 56 | |
| 57 | def __init__(self, resumable_progress, total_size): |
| 58 | """Constructor. |
| 59 | |
| 60 | Args: |
| 61 | resumable_progress: int, bytes sent so far. |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 62 | total_size: int, total bytes in complete upload, or None if the total |
| 63 | upload size isn't known ahead of time. |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 64 | """ |
| 65 | self.resumable_progress = resumable_progress |
| 66 | self.total_size = total_size |
| 67 | |
| 68 | def progress(self): |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 69 | """Percent of upload completed, as a float. |
| 70 | |
| 71 | Returns: |
| 72 | the percentage complete as a float, returning 0.0 if the total size of |
| 73 | the upload is unknown. |
| 74 | """ |
| 75 | if self.total_size is not None: |
| 76 | return float(self.resumable_progress) / float(self.total_size) |
| 77 | else: |
| 78 | return 0.0 |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 79 | |
| 80 | |
Joe Gregorio | 708388c | 2012-06-15 13:43:04 -0400 | [diff] [blame] | 81 | class MediaDownloadProgress(object): |
| 82 | """Status of a resumable download.""" |
| 83 | |
| 84 | def __init__(self, resumable_progress, total_size): |
| 85 | """Constructor. |
| 86 | |
| 87 | Args: |
| 88 | resumable_progress: int, bytes received so far. |
| 89 | total_size: int, total bytes in complete download. |
| 90 | """ |
| 91 | self.resumable_progress = resumable_progress |
| 92 | self.total_size = total_size |
| 93 | |
| 94 | def progress(self): |
| 95 | """Percent of download completed, as a float. |
| 96 | |
| 97 | Returns: |
| 98 | the percentage complete as a float, returning 0.0 if the total size of |
| 99 | the download is unknown. |
| 100 | """ |
| 101 | if self.total_size is not None: |
| 102 | return float(self.resumable_progress) / float(self.total_size) |
| 103 | else: |
| 104 | return 0.0 |
| 105 | |
| 106 | |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 107 | class MediaUpload(object): |
| 108 | """Describes a media object to upload. |
| 109 | |
| 110 | Base class that defines the interface of MediaUpload subclasses. |
Joe Gregorio | 88f699f | 2012-06-07 13:36:06 -0400 | [diff] [blame] | 111 | |
| 112 | Note that subclasses of MediaUpload may allow you to control the chunksize |
| 113 | when upload a media object. It is important to keep the size of the chunk as |
| 114 | large as possible to keep the upload efficient. Other factors may influence |
| 115 | the size of the chunk you use, particularly if you are working in an |
| 116 | environment where individual HTTP requests may have a hardcoded time limit, |
| 117 | such as under certain classes of requests under Google App Engine. |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 118 | """ |
| 119 | |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 120 | def chunksize(self): |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 121 | """Chunk size for resumable uploads. |
| 122 | |
| 123 | Returns: |
| 124 | Chunk size in bytes. |
| 125 | """ |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 126 | raise NotImplementedError() |
| 127 | |
| 128 | def mimetype(self): |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 129 | """Mime type of the body. |
| 130 | |
| 131 | Returns: |
| 132 | Mime type. |
| 133 | """ |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 134 | return 'application/octet-stream' |
| 135 | |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 136 | def size(self): |
| 137 | """Size of upload. |
| 138 | |
| 139 | Returns: |
| 140 | Size of the body, or None of the size is unknown. |
| 141 | """ |
| 142 | return None |
| 143 | |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 144 | def resumable(self): |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 145 | """Whether this upload is resumable. |
| 146 | |
| 147 | Returns: |
| 148 | True if resumable upload or False. |
| 149 | """ |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 150 | return False |
| 151 | |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 152 | def getbytes(self, begin, end): |
| 153 | """Get bytes from the media. |
| 154 | |
| 155 | Args: |
| 156 | begin: int, offset from beginning of file. |
| 157 | length: int, number of bytes to read, starting at begin. |
| 158 | |
| 159 | Returns: |
| 160 | A string of bytes read. May be shorter than length if EOF was reached |
| 161 | first. |
| 162 | """ |
| 163 | raise NotImplementedError() |
| 164 | |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 165 | def _to_json(self, strip=None): |
| 166 | """Utility function for creating a JSON representation of a MediaUpload. |
| 167 | |
| 168 | Args: |
| 169 | strip: array, An array of names of members to not include in the JSON. |
| 170 | |
| 171 | Returns: |
| 172 | string, a JSON representation of this instance, suitable to pass to |
| 173 | from_json(). |
| 174 | """ |
| 175 | t = type(self) |
| 176 | d = copy.copy(self.__dict__) |
| 177 | if strip is not None: |
| 178 | for member in strip: |
| 179 | del d[member] |
| 180 | d['_class'] = t.__name__ |
| 181 | d['_module'] = t.__module__ |
| 182 | return simplejson.dumps(d) |
| 183 | |
| 184 | def to_json(self): |
| 185 | """Create a JSON representation of an instance of MediaUpload. |
| 186 | |
| 187 | Returns: |
| 188 | string, a JSON representation of this instance, suitable to pass to |
| 189 | from_json(). |
| 190 | """ |
| 191 | return self._to_json() |
| 192 | |
| 193 | @classmethod |
| 194 | def new_from_json(cls, s): |
| 195 | """Utility class method to instantiate a MediaUpload subclass from a JSON |
| 196 | representation produced by to_json(). |
| 197 | |
| 198 | Args: |
| 199 | s: string, JSON from to_json(). |
| 200 | |
| 201 | Returns: |
| 202 | An instance of the subclass of MediaUpload that was serialized with |
| 203 | to_json(). |
| 204 | """ |
| 205 | data = simplejson.loads(s) |
| 206 | # Find and call the right classmethod from_json() to restore the object. |
| 207 | module = data['_module'] |
| 208 | m = __import__(module, fromlist=module.split('.')[:-1]) |
| 209 | kls = getattr(m, data['_class']) |
| 210 | from_json = getattr(kls, 'from_json') |
| 211 | return from_json(s) |
| 212 | |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 213 | |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 214 | class MediaFileUpload(MediaUpload): |
| 215 | """A MediaUpload for a file. |
| 216 | |
| 217 | Construct a MediaFileUpload and pass as the media_body parameter of the |
| 218 | method. For example, if we had a service that allowed uploading images: |
| 219 | |
| 220 | |
Joe Gregorio | 7ceb26f | 2012-06-15 13:57:26 -0400 | [diff] [blame] | 221 | media = MediaFileUpload('cow.png', mimetype='image/png', |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 222 | chunksize=1024*1024, resumable=True) |
Joe Gregorio | 7ceb26f | 2012-06-15 13:57:26 -0400 | [diff] [blame] | 223 | farm.animals()..insert( |
| 224 | id='cow', |
| 225 | name='cow.png', |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 226 | media_body=media).execute() |
| 227 | """ |
| 228 | |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 229 | def __init__(self, filename, mimetype=None, chunksize=DEFAULT_CHUNK_SIZE, resumable=False): |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 230 | """Constructor. |
| 231 | |
| 232 | Args: |
| 233 | filename: string, Name of the file. |
| 234 | mimetype: string, Mime-type of the file. If None then a mime-type will be |
| 235 | guessed from the file extension. |
| 236 | chunksize: int, File will be uploaded in chunks of this many bytes. Only |
| 237 | used if resumable=True. |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 238 | resumable: bool, True if this is a resumable upload. False means upload |
| 239 | in a single request. |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 240 | """ |
| 241 | self._filename = filename |
| 242 | self._size = os.path.getsize(filename) |
| 243 | self._fd = None |
| 244 | if mimetype is None: |
| 245 | (mimetype, encoding) = mimetypes.guess_type(filename) |
| 246 | self._mimetype = mimetype |
| 247 | self._chunksize = chunksize |
| 248 | self._resumable = resumable |
| 249 | |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 250 | def chunksize(self): |
| 251 | """Chunk size for resumable uploads. |
| 252 | |
| 253 | Returns: |
| 254 | Chunk size in bytes. |
| 255 | """ |
| 256 | return self._chunksize |
| 257 | |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 258 | def mimetype(self): |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 259 | """Mime type of the body. |
| 260 | |
| 261 | Returns: |
| 262 | Mime type. |
| 263 | """ |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 264 | return self._mimetype |
| 265 | |
| 266 | def size(self): |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 267 | """Size of upload. |
| 268 | |
| 269 | Returns: |
| 270 | Size of the body, or None of the size is unknown. |
| 271 | """ |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 272 | return self._size |
| 273 | |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 274 | def resumable(self): |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 275 | """Whether this upload is resumable. |
| 276 | |
| 277 | Returns: |
| 278 | True if resumable upload or False. |
| 279 | """ |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 280 | return self._resumable |
| 281 | |
| 282 | def getbytes(self, begin, length): |
| 283 | """Get bytes from the media. |
| 284 | |
| 285 | Args: |
| 286 | begin: int, offset from beginning of file. |
| 287 | length: int, number of bytes to read, starting at begin. |
| 288 | |
| 289 | Returns: |
| 290 | A string of bytes read. May be shorted than length if EOF was reached |
| 291 | first. |
| 292 | """ |
| 293 | if self._fd is None: |
| 294 | self._fd = open(self._filename, 'rb') |
| 295 | self._fd.seek(begin) |
| 296 | return self._fd.read(length) |
| 297 | |
| 298 | def to_json(self): |
Joe Gregorio | 708388c | 2012-06-15 13:43:04 -0400 | [diff] [blame] | 299 | """Creating a JSON representation of an instance of MediaFileUpload. |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 300 | |
| 301 | Returns: |
| 302 | string, a JSON representation of this instance, suitable to pass to |
| 303 | from_json(). |
| 304 | """ |
| 305 | return self._to_json(['_fd']) |
| 306 | |
| 307 | @staticmethod |
| 308 | def from_json(s): |
| 309 | d = simplejson.loads(s) |
| 310 | return MediaFileUpload( |
| 311 | d['_filename'], d['_mimetype'], d['_chunksize'], d['_resumable']) |
| 312 | |
| 313 | |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 314 | class MediaIoBaseUpload(MediaUpload): |
| 315 | """A MediaUpload for a io.Base objects. |
| 316 | |
| 317 | Note that the Python file object is compatible with io.Base and can be used |
| 318 | with this class also. |
| 319 | |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 320 | fh = io.BytesIO('...Some data to upload...') |
| 321 | media = MediaIoBaseUpload(fh, mimetype='image/png', |
| 322 | chunksize=1024*1024, resumable=True) |
Joe Gregorio | 7ceb26f | 2012-06-15 13:57:26 -0400 | [diff] [blame] | 323 | farm.animals().insert( |
| 324 | id='cow', |
| 325 | name='cow.png', |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 326 | media_body=media).execute() |
| 327 | """ |
| 328 | |
Joe Gregorio | 4a2c29f | 2012-07-12 12:52:47 -0400 | [diff] [blame] | 329 | def __init__(self, fd, mimetype, chunksize=DEFAULT_CHUNK_SIZE, |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 330 | resumable=False): |
| 331 | """Constructor. |
| 332 | |
| 333 | Args: |
Joe Gregorio | 4a2c29f | 2012-07-12 12:52:47 -0400 | [diff] [blame] | 334 | fd: io.Base or file object, The source of the bytes to upload. MUST be |
Joe Gregorio | 44454e4 | 2012-06-15 08:38:53 -0400 | [diff] [blame] | 335 | opened in blocking mode, do not use streams opened in non-blocking mode. |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 336 | mimetype: string, Mime-type of the file. If None then a mime-type will be |
| 337 | guessed from the file extension. |
| 338 | chunksize: int, File will be uploaded in chunks of this many bytes. Only |
| 339 | used if resumable=True. |
| 340 | resumable: bool, True if this is a resumable upload. False means upload |
| 341 | in a single request. |
| 342 | """ |
Joe Gregorio | 4a2c29f | 2012-07-12 12:52:47 -0400 | [diff] [blame] | 343 | self._fd = fd |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 344 | self._mimetype = mimetype |
| 345 | self._chunksize = chunksize |
| 346 | self._resumable = resumable |
| 347 | self._size = None |
| 348 | try: |
Joe Gregorio | 4a2c29f | 2012-07-12 12:52:47 -0400 | [diff] [blame] | 349 | if hasattr(self._fd, 'fileno'): |
| 350 | fileno = self._fd.fileno() |
Joe Gregorio | 44454e4 | 2012-06-15 08:38:53 -0400 | [diff] [blame] | 351 | |
| 352 | # Pipes and such show up as 0 length files. |
| 353 | size = os.fstat(fileno).st_size |
| 354 | if size: |
| 355 | self._size = os.fstat(fileno).st_size |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 356 | except IOError: |
| 357 | pass |
| 358 | |
| 359 | def chunksize(self): |
| 360 | """Chunk size for resumable uploads. |
| 361 | |
| 362 | Returns: |
| 363 | Chunk size in bytes. |
| 364 | """ |
| 365 | return self._chunksize |
| 366 | |
| 367 | def mimetype(self): |
| 368 | """Mime type of the body. |
| 369 | |
| 370 | Returns: |
| 371 | Mime type. |
| 372 | """ |
| 373 | return self._mimetype |
| 374 | |
| 375 | def size(self): |
| 376 | """Size of upload. |
| 377 | |
| 378 | Returns: |
| 379 | Size of the body, or None of the size is unknown. |
| 380 | """ |
| 381 | return self._size |
| 382 | |
| 383 | def resumable(self): |
| 384 | """Whether this upload is resumable. |
| 385 | |
| 386 | Returns: |
| 387 | True if resumable upload or False. |
| 388 | """ |
| 389 | return self._resumable |
| 390 | |
| 391 | def getbytes(self, begin, length): |
| 392 | """Get bytes from the media. |
| 393 | |
| 394 | Args: |
| 395 | begin: int, offset from beginning of file. |
| 396 | length: int, number of bytes to read, starting at begin. |
| 397 | |
| 398 | Returns: |
| 399 | A string of bytes read. May be shorted than length if EOF was reached |
| 400 | first. |
| 401 | """ |
Joe Gregorio | 4a2c29f | 2012-07-12 12:52:47 -0400 | [diff] [blame] | 402 | self._fd.seek(begin) |
| 403 | return self._fd.read(length) |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 404 | |
| 405 | def to_json(self): |
| 406 | """This upload type is not serializable.""" |
| 407 | raise NotImplementedError('MediaIoBaseUpload is not serializable.') |
| 408 | |
| 409 | |
Ali Afshar | 6f11ea1 | 2012-02-07 10:32:14 -0500 | [diff] [blame] | 410 | class MediaInMemoryUpload(MediaUpload): |
| 411 | """MediaUpload for a chunk of bytes. |
| 412 | |
| 413 | Construct a MediaFileUpload and pass as the media_body parameter of the |
Joe Gregorio | 7ceb26f | 2012-06-15 13:57:26 -0400 | [diff] [blame] | 414 | method. |
Ali Afshar | 6f11ea1 | 2012-02-07 10:32:14 -0500 | [diff] [blame] | 415 | """ |
| 416 | |
| 417 | def __init__(self, body, mimetype='application/octet-stream', |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 418 | chunksize=DEFAULT_CHUNK_SIZE, resumable=False): |
Ali Afshar | 6f11ea1 | 2012-02-07 10:32:14 -0500 | [diff] [blame] | 419 | """Create a new MediaBytesUpload. |
| 420 | |
| 421 | Args: |
| 422 | body: string, Bytes of body content. |
| 423 | mimetype: string, Mime-type of the file or default of |
| 424 | 'application/octet-stream'. |
| 425 | chunksize: int, File will be uploaded in chunks of this many bytes. Only |
| 426 | used if resumable=True. |
| 427 | resumable: bool, True if this is a resumable upload. False means upload |
| 428 | in a single request. |
| 429 | """ |
| 430 | self._body = body |
| 431 | self._mimetype = mimetype |
| 432 | self._resumable = resumable |
| 433 | self._chunksize = chunksize |
| 434 | |
| 435 | def chunksize(self): |
| 436 | """Chunk size for resumable uploads. |
| 437 | |
| 438 | Returns: |
| 439 | Chunk size in bytes. |
| 440 | """ |
| 441 | return self._chunksize |
| 442 | |
| 443 | def mimetype(self): |
| 444 | """Mime type of the body. |
| 445 | |
| 446 | Returns: |
| 447 | Mime type. |
| 448 | """ |
| 449 | return self._mimetype |
| 450 | |
| 451 | def size(self): |
| 452 | """Size of upload. |
| 453 | |
| 454 | Returns: |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 455 | Size of the body, or None of the size is unknown. |
Ali Afshar | 6f11ea1 | 2012-02-07 10:32:14 -0500 | [diff] [blame] | 456 | """ |
Ali Afshar | 1cb6b67 | 2012-03-12 08:46:14 -0400 | [diff] [blame] | 457 | return len(self._body) |
Ali Afshar | 6f11ea1 | 2012-02-07 10:32:14 -0500 | [diff] [blame] | 458 | |
| 459 | def resumable(self): |
| 460 | """Whether this upload is resumable. |
| 461 | |
| 462 | Returns: |
| 463 | True if resumable upload or False. |
| 464 | """ |
| 465 | return self._resumable |
| 466 | |
| 467 | def getbytes(self, begin, length): |
| 468 | """Get bytes from the media. |
| 469 | |
| 470 | Args: |
| 471 | begin: int, offset from beginning of file. |
| 472 | length: int, number of bytes to read, starting at begin. |
| 473 | |
| 474 | Returns: |
| 475 | A string of bytes read. May be shorter than length if EOF was reached |
| 476 | first. |
| 477 | """ |
| 478 | return self._body[begin:begin + length] |
| 479 | |
| 480 | def to_json(self): |
| 481 | """Create a JSON representation of a MediaInMemoryUpload. |
| 482 | |
| 483 | Returns: |
| 484 | string, a JSON representation of this instance, suitable to pass to |
| 485 | from_json(). |
| 486 | """ |
| 487 | t = type(self) |
| 488 | d = copy.copy(self.__dict__) |
| 489 | del d['_body'] |
| 490 | d['_class'] = t.__name__ |
| 491 | d['_module'] = t.__module__ |
| 492 | d['_b64body'] = base64.b64encode(self._body) |
| 493 | return simplejson.dumps(d) |
| 494 | |
| 495 | @staticmethod |
| 496 | def from_json(s): |
| 497 | d = simplejson.loads(s) |
| 498 | return MediaInMemoryUpload(base64.b64decode(d['_b64body']), |
| 499 | d['_mimetype'], d['_chunksize'], |
| 500 | d['_resumable']) |
| 501 | |
| 502 | |
Joe Gregorio | 708388c | 2012-06-15 13:43:04 -0400 | [diff] [blame] | 503 | class MediaIoBaseDownload(object): |
| 504 | """"Download media resources. |
| 505 | |
| 506 | Note that the Python file object is compatible with io.Base and can be used |
| 507 | with this class also. |
| 508 | |
| 509 | |
| 510 | Example: |
Joe Gregorio | 7ceb26f | 2012-06-15 13:57:26 -0400 | [diff] [blame] | 511 | request = farms.animals().get_media(id='cow') |
| 512 | fh = io.FileIO('cow.png', mode='wb') |
Joe Gregorio | 708388c | 2012-06-15 13:43:04 -0400 | [diff] [blame] | 513 | downloader = MediaIoBaseDownload(fh, request, chunksize=1024*1024) |
| 514 | |
| 515 | done = False |
| 516 | while done is False: |
| 517 | status, done = downloader.next_chunk() |
| 518 | if status: |
| 519 | print "Download %d%%." % int(status.progress() * 100) |
| 520 | print "Download Complete!" |
| 521 | """ |
| 522 | |
Joe Gregorio | 4a2c29f | 2012-07-12 12:52:47 -0400 | [diff] [blame] | 523 | def __init__(self, fd, request, chunksize=DEFAULT_CHUNK_SIZE): |
Joe Gregorio | 708388c | 2012-06-15 13:43:04 -0400 | [diff] [blame] | 524 | """Constructor. |
| 525 | |
| 526 | Args: |
Joe Gregorio | 4a2c29f | 2012-07-12 12:52:47 -0400 | [diff] [blame] | 527 | fd: io.Base or file object, The stream in which to write the downloaded |
Joe Gregorio | 708388c | 2012-06-15 13:43:04 -0400 | [diff] [blame] | 528 | bytes. |
| 529 | request: apiclient.http.HttpRequest, the media request to perform in |
| 530 | chunks. |
| 531 | chunksize: int, File will be downloaded in chunks of this many bytes. |
| 532 | """ |
Joe Gregorio | 4a2c29f | 2012-07-12 12:52:47 -0400 | [diff] [blame] | 533 | self._fd = fd |
| 534 | self._request = request |
| 535 | self._uri = request.uri |
| 536 | self._chunksize = chunksize |
| 537 | self._progress = 0 |
| 538 | self._total_size = None |
| 539 | self._done = False |
Joe Gregorio | 708388c | 2012-06-15 13:43:04 -0400 | [diff] [blame] | 540 | |
| 541 | def next_chunk(self): |
| 542 | """Get the next chunk of the download. |
| 543 | |
| 544 | Returns: |
| 545 | (status, done): (MediaDownloadStatus, boolean) |
| 546 | The value of 'done' will be True when the media has been fully |
| 547 | downloaded. |
| 548 | |
| 549 | Raises: |
| 550 | apiclient.errors.HttpError if the response was not a 2xx. |
Joe Gregorio | 77af30a | 2012-08-01 14:54:40 -0400 | [diff] [blame] | 551 | httplib2.HttpLib2Error if a transport error has occured. |
Joe Gregorio | 708388c | 2012-06-15 13:43:04 -0400 | [diff] [blame] | 552 | """ |
| 553 | headers = { |
| 554 | 'range': 'bytes=%d-%d' % ( |
Joe Gregorio | 4a2c29f | 2012-07-12 12:52:47 -0400 | [diff] [blame] | 555 | self._progress, self._progress + self._chunksize) |
Joe Gregorio | 708388c | 2012-06-15 13:43:04 -0400 | [diff] [blame] | 556 | } |
Joe Gregorio | 4a2c29f | 2012-07-12 12:52:47 -0400 | [diff] [blame] | 557 | http = self._request.http |
Joe Gregorio | 708388c | 2012-06-15 13:43:04 -0400 | [diff] [blame] | 558 | http.follow_redirects = False |
| 559 | |
Joe Gregorio | 4a2c29f | 2012-07-12 12:52:47 -0400 | [diff] [blame] | 560 | resp, content = http.request(self._uri, headers=headers) |
Joe Gregorio | 708388c | 2012-06-15 13:43:04 -0400 | [diff] [blame] | 561 | if resp.status in [301, 302, 303, 307, 308] and 'location' in resp: |
Joe Gregorio | 4a2c29f | 2012-07-12 12:52:47 -0400 | [diff] [blame] | 562 | self._uri = resp['location'] |
| 563 | resp, content = http.request(self._uri, headers=headers) |
Joe Gregorio | 708388c | 2012-06-15 13:43:04 -0400 | [diff] [blame] | 564 | if resp.status in [200, 206]: |
Joe Gregorio | 4a2c29f | 2012-07-12 12:52:47 -0400 | [diff] [blame] | 565 | self._progress += len(content) |
| 566 | self._fd.write(content) |
Joe Gregorio | 708388c | 2012-06-15 13:43:04 -0400 | [diff] [blame] | 567 | |
| 568 | if 'content-range' in resp: |
| 569 | content_range = resp['content-range'] |
| 570 | length = content_range.rsplit('/', 1)[1] |
Joe Gregorio | 4a2c29f | 2012-07-12 12:52:47 -0400 | [diff] [blame] | 571 | self._total_size = int(length) |
Joe Gregorio | 708388c | 2012-06-15 13:43:04 -0400 | [diff] [blame] | 572 | |
Joe Gregorio | 4a2c29f | 2012-07-12 12:52:47 -0400 | [diff] [blame] | 573 | if self._progress == self._total_size: |
| 574 | self._done = True |
| 575 | return MediaDownloadProgress(self._progress, self._total_size), self._done |
Joe Gregorio | 708388c | 2012-06-15 13:43:04 -0400 | [diff] [blame] | 576 | else: |
Joe Gregorio | 4a2c29f | 2012-07-12 12:52:47 -0400 | [diff] [blame] | 577 | raise HttpError(resp, content, self._uri) |
Joe Gregorio | 708388c | 2012-06-15 13:43:04 -0400 | [diff] [blame] | 578 | |
| 579 | |
Joe Gregorio | c5c5a37 | 2010-09-22 11:42:32 -0400 | [diff] [blame] | 580 | class HttpRequest(object): |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 581 | """Encapsulates a single HTTP request.""" |
Joe Gregorio | c5c5a37 | 2010-09-22 11:42:32 -0400 | [diff] [blame] | 582 | |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 583 | def __init__(self, http, postproc, uri, |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 584 | method='GET', |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 585 | body=None, |
| 586 | headers=None, |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 587 | methodId=None, |
| 588 | resumable=None): |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 589 | """Constructor for an HttpRequest. |
| 590 | |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 591 | Args: |
| 592 | http: httplib2.Http, the transport object to use to make a request |
Joe Gregorio | abda96f | 2011-02-11 20:19:33 -0500 | [diff] [blame] | 593 | postproc: callable, called on the HTTP response and content to transform |
| 594 | it into a data object before returning, or raising an exception |
| 595 | on an error. |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 596 | uri: string, the absolute URI to send the request to |
| 597 | method: string, the HTTP method to use |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 598 | body: string, the request body of the HTTP request, |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 599 | headers: dict, the HTTP request headers |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 600 | methodId: string, a unique identifier for the API method being called. |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 601 | resumable: MediaUpload, None if this is not a resumbale request. |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 602 | """ |
Joe Gregorio | c5c5a37 | 2010-09-22 11:42:32 -0400 | [diff] [blame] | 603 | self.uri = uri |
| 604 | self.method = method |
| 605 | self.body = body |
| 606 | self.headers = headers or {} |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 607 | self.methodId = methodId |
Joe Gregorio | c5c5a37 | 2010-09-22 11:42:32 -0400 | [diff] [blame] | 608 | self.http = http |
| 609 | self.postproc = postproc |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 610 | self.resumable = resumable |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 611 | self._in_error_state = False |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 612 | |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 613 | # Pull the multipart boundary out of the content-type header. |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 614 | major, minor, params = mimeparse.parse_mime_type( |
| 615 | headers.get('content-type', 'application/json')) |
Joe Gregorio | bd512b5 | 2011-12-06 15:39:26 -0500 | [diff] [blame] | 616 | |
Joe Gregorio | 945be3e | 2012-01-27 17:01:06 -0500 | [diff] [blame] | 617 | # The size of the non-media part of the request. |
| 618 | self.body_size = len(self.body or '') |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 619 | |
| 620 | # The resumable URI to send chunks to. |
| 621 | self.resumable_uri = None |
| 622 | |
| 623 | # The bytes that have been uploaded. |
| 624 | self.resumable_progress = 0 |
| 625 | |
Joe Gregorio | c5c5a37 | 2010-09-22 11:42:32 -0400 | [diff] [blame] | 626 | def execute(self, http=None): |
| 627 | """Execute the request. |
| 628 | |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 629 | Args: |
| 630 | http: httplib2.Http, an http object to be used in place of the |
| 631 | one the HttpRequest request object was constructed with. |
| 632 | |
| 633 | Returns: |
| 634 | A deserialized object model of the response body as determined |
| 635 | by the postproc. |
| 636 | |
| 637 | Raises: |
| 638 | apiclient.errors.HttpError if the response was not a 2xx. |
Joe Gregorio | 77af30a | 2012-08-01 14:54:40 -0400 | [diff] [blame] | 639 | httplib2.HttpLib2Error if a transport error has occured. |
Joe Gregorio | c5c5a37 | 2010-09-22 11:42:32 -0400 | [diff] [blame] | 640 | """ |
| 641 | if http is None: |
| 642 | http = self.http |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 643 | if self.resumable: |
| 644 | body = None |
| 645 | while body is None: |
| 646 | _, body = self.next_chunk(http) |
| 647 | return body |
| 648 | else: |
Joe Gregorio | 884e2b2 | 2012-02-24 09:37:00 -0500 | [diff] [blame] | 649 | if 'content-length' not in self.headers: |
| 650 | self.headers['content-length'] = str(self.body_size) |
Joe Gregorio | ba5c790 | 2012-08-03 12:48:16 -0400 | [diff] [blame^] | 651 | # If the request URI is too long then turn it into a POST request. |
| 652 | if len(self.uri) > MAX_URI_LENGTH and self.method == 'GET': |
| 653 | self.method = 'POST' |
| 654 | self.headers['x-http-method-override'] = 'GET' |
| 655 | self.headers['content-type'] = 'application/x-www-form-urlencoded' |
| 656 | parsed = urlparse.urlparse(self.uri) |
| 657 | self.uri = urlparse.urlunparse( |
| 658 | (parsed.scheme, parsed.netloc, parsed.path, parsed.params, None, |
| 659 | None) |
| 660 | ) |
| 661 | self.body = parsed.query |
| 662 | self.headers['content-length'] = str(len(self.body)) |
| 663 | |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 664 | resp, content = http.request(self.uri, self.method, |
| 665 | body=self.body, |
| 666 | headers=self.headers) |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 667 | if resp.status >= 300: |
| 668 | raise HttpError(resp, content, self.uri) |
Joe Gregorio | c5c5a37 | 2010-09-22 11:42:32 -0400 | [diff] [blame] | 669 | return self.postproc(resp, content) |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 670 | |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 671 | def next_chunk(self, http=None): |
| 672 | """Execute the next step of a resumable upload. |
| 673 | |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 674 | Can only be used if the method being executed supports media uploads and |
| 675 | the MediaUpload object passed in was flagged as using resumable upload. |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 676 | |
| 677 | Example: |
| 678 | |
Joe Gregorio | 7ceb26f | 2012-06-15 13:57:26 -0400 | [diff] [blame] | 679 | media = MediaFileUpload('cow.png', mimetype='image/png', |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 680 | chunksize=1000, resumable=True) |
Joe Gregorio | 7ceb26f | 2012-06-15 13:57:26 -0400 | [diff] [blame] | 681 | request = farm.animals().insert( |
| 682 | id='cow', |
| 683 | name='cow.png', |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 684 | media_body=media) |
| 685 | |
| 686 | response = None |
| 687 | while response is None: |
| 688 | status, response = request.next_chunk() |
| 689 | if status: |
| 690 | print "Upload %d%% complete." % int(status.progress() * 100) |
| 691 | |
| 692 | |
| 693 | Returns: |
| 694 | (status, body): (ResumableMediaStatus, object) |
| 695 | The body will be None until the resumable media is fully uploaded. |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 696 | |
| 697 | Raises: |
| 698 | apiclient.errors.HttpError if the response was not a 2xx. |
Joe Gregorio | 77af30a | 2012-08-01 14:54:40 -0400 | [diff] [blame] | 699 | httplib2.HttpLib2Error if a transport error has occured. |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 700 | """ |
| 701 | if http is None: |
| 702 | http = self.http |
| 703 | |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 704 | if self.resumable.size() is None: |
| 705 | size = '*' |
| 706 | else: |
| 707 | size = str(self.resumable.size()) |
| 708 | |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 709 | if self.resumable_uri is None: |
| 710 | start_headers = copy.copy(self.headers) |
| 711 | start_headers['X-Upload-Content-Type'] = self.resumable.mimetype() |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 712 | if size != '*': |
| 713 | start_headers['X-Upload-Content-Length'] = size |
Joe Gregorio | 945be3e | 2012-01-27 17:01:06 -0500 | [diff] [blame] | 714 | start_headers['content-length'] = str(self.body_size) |
| 715 | |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 716 | resp, content = http.request(self.uri, self.method, |
Joe Gregorio | 945be3e | 2012-01-27 17:01:06 -0500 | [diff] [blame] | 717 | body=self.body, |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 718 | headers=start_headers) |
| 719 | if resp.status == 200 and 'location' in resp: |
| 720 | self.resumable_uri = resp['location'] |
| 721 | else: |
| 722 | raise ResumableUploadError("Failed to retrieve starting URI.") |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 723 | elif self._in_error_state: |
| 724 | # If we are in an error state then query the server for current state of |
| 725 | # the upload by sending an empty PUT and reading the 'range' header in |
| 726 | # the response. |
| 727 | headers = { |
| 728 | 'Content-Range': 'bytes */%s' % size, |
| 729 | 'content-length': '0' |
| 730 | } |
| 731 | resp, content = http.request(self.resumable_uri, 'PUT', |
| 732 | headers=headers) |
| 733 | status, body = self._process_response(resp, content) |
| 734 | if body: |
| 735 | # The upload was complete. |
| 736 | return (status, body) |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 737 | |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 738 | data = self.resumable.getbytes( |
| 739 | self.resumable_progress, self.resumable.chunksize()) |
Joe Gregorio | 44454e4 | 2012-06-15 08:38:53 -0400 | [diff] [blame] | 740 | |
| 741 | # A short read implies that we are at EOF, so finish the upload. |
| 742 | if len(data) < self.resumable.chunksize(): |
| 743 | size = str(self.resumable_progress + len(data)) |
| 744 | |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 745 | headers = { |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 746 | 'Content-Range': 'bytes %d-%d/%s' % ( |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 747 | self.resumable_progress, self.resumable_progress + len(data) - 1, |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 748 | size) |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 749 | } |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 750 | try: |
| 751 | resp, content = http.request(self.resumable_uri, 'PUT', |
| 752 | body=data, |
| 753 | headers=headers) |
| 754 | except: |
| 755 | self._in_error_state = True |
| 756 | raise |
| 757 | |
| 758 | return self._process_response(resp, content) |
| 759 | |
| 760 | def _process_response(self, resp, content): |
| 761 | """Process the response from a single chunk upload. |
| 762 | |
| 763 | Args: |
| 764 | resp: httplib2.Response, the response object. |
| 765 | content: string, the content of the response. |
| 766 | |
| 767 | Returns: |
| 768 | (status, body): (ResumableMediaStatus, object) |
| 769 | The body will be None until the resumable media is fully uploaded. |
| 770 | |
| 771 | Raises: |
| 772 | apiclient.errors.HttpError if the response was not a 2xx or a 308. |
| 773 | """ |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 774 | if resp.status in [200, 201]: |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 775 | self._in_error_state = False |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 776 | return None, self.postproc(resp, content) |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 777 | elif resp.status == 308: |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 778 | self._in_error_state = False |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 779 | # A "308 Resume Incomplete" indicates we are not done. |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 780 | self.resumable_progress = int(resp['range'].split('-')[1]) + 1 |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 781 | if 'location' in resp: |
| 782 | self.resumable_uri = resp['location'] |
| 783 | else: |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 784 | self._in_error_state = True |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 785 | raise HttpError(resp, content, self.uri) |
| 786 | |
Joe Gregorio | 945be3e | 2012-01-27 17:01:06 -0500 | [diff] [blame] | 787 | return (MediaUploadProgress(self.resumable_progress, self.resumable.size()), |
| 788 | None) |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 789 | |
| 790 | def to_json(self): |
| 791 | """Returns a JSON representation of the HttpRequest.""" |
| 792 | d = copy.copy(self.__dict__) |
| 793 | if d['resumable'] is not None: |
| 794 | d['resumable'] = self.resumable.to_json() |
| 795 | del d['http'] |
| 796 | del d['postproc'] |
Joe Gregorio | 910b9b1 | 2012-06-12 09:36:30 -0400 | [diff] [blame] | 797 | |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 798 | return simplejson.dumps(d) |
| 799 | |
| 800 | @staticmethod |
| 801 | def from_json(s, http, postproc): |
| 802 | """Returns an HttpRequest populated with info from a JSON object.""" |
| 803 | d = simplejson.loads(s) |
| 804 | if d['resumable'] is not None: |
| 805 | d['resumable'] = MediaUpload.new_from_json(d['resumable']) |
| 806 | return HttpRequest( |
| 807 | http, |
| 808 | postproc, |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 809 | uri=d['uri'], |
| 810 | method=d['method'], |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 811 | body=d['body'], |
| 812 | headers=d['headers'], |
| 813 | methodId=d['methodId'], |
| 814 | resumable=d['resumable']) |
| 815 | |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 816 | |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 817 | class BatchHttpRequest(object): |
Joe Gregorio | ebd0b84 | 2012-06-15 14:14:17 -0400 | [diff] [blame] | 818 | """Batches multiple HttpRequest objects into a single HTTP request. |
| 819 | |
| 820 | Example: |
| 821 | from apiclient.http import BatchHttpRequest |
| 822 | |
Joe Gregorio | e7a0c47 | 2012-07-12 11:46:04 -0400 | [diff] [blame] | 823 | def list_animals(request_id, response, exception): |
Joe Gregorio | ebd0b84 | 2012-06-15 14:14:17 -0400 | [diff] [blame] | 824 | \"\"\"Do something with the animals list response.\"\"\" |
Joe Gregorio | e7a0c47 | 2012-07-12 11:46:04 -0400 | [diff] [blame] | 825 | if exception is not None: |
| 826 | # Do something with the exception. |
| 827 | pass |
| 828 | else: |
| 829 | # Do something with the response. |
| 830 | pass |
Joe Gregorio | ebd0b84 | 2012-06-15 14:14:17 -0400 | [diff] [blame] | 831 | |
Joe Gregorio | e7a0c47 | 2012-07-12 11:46:04 -0400 | [diff] [blame] | 832 | def list_farmers(request_id, response, exception): |
Joe Gregorio | ebd0b84 | 2012-06-15 14:14:17 -0400 | [diff] [blame] | 833 | \"\"\"Do something with the farmers list response.\"\"\" |
Joe Gregorio | e7a0c47 | 2012-07-12 11:46:04 -0400 | [diff] [blame] | 834 | if exception is not None: |
| 835 | # Do something with the exception. |
| 836 | pass |
| 837 | else: |
| 838 | # Do something with the response. |
| 839 | pass |
Joe Gregorio | ebd0b84 | 2012-06-15 14:14:17 -0400 | [diff] [blame] | 840 | |
| 841 | service = build('farm', 'v2') |
| 842 | |
| 843 | batch = BatchHttpRequest() |
| 844 | |
| 845 | batch.add(service.animals().list(), list_animals) |
| 846 | batch.add(service.farmers().list(), list_farmers) |
| 847 | batch.execute(http) |
| 848 | """ |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 849 | |
| 850 | def __init__(self, callback=None, batch_uri=None): |
| 851 | """Constructor for a BatchHttpRequest. |
| 852 | |
| 853 | Args: |
| 854 | callback: callable, A callback to be called for each response, of the |
Joe Gregorio | 4fbde1c | 2012-07-11 14:47:39 -0400 | [diff] [blame] | 855 | form callback(id, response, exception). The first parameter is the |
| 856 | request id, and the second is the deserialized response object. The |
| 857 | third is an apiclient.errors.HttpError exception object if an HTTP error |
| 858 | occurred while processing the request, or None if no error occurred. |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 859 | batch_uri: string, URI to send batch requests to. |
| 860 | """ |
| 861 | if batch_uri is None: |
| 862 | batch_uri = 'https://www.googleapis.com/batch' |
| 863 | self._batch_uri = batch_uri |
| 864 | |
| 865 | # Global callback to be called for each individual response in the batch. |
| 866 | self._callback = callback |
| 867 | |
Joe Gregorio | 654f4a2 | 2012-02-09 14:15:44 -0500 | [diff] [blame] | 868 | # A map from id to request. |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 869 | self._requests = {} |
| 870 | |
Joe Gregorio | 654f4a2 | 2012-02-09 14:15:44 -0500 | [diff] [blame] | 871 | # A map from id to callback. |
| 872 | self._callbacks = {} |
| 873 | |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 874 | # List of request ids, in the order in which they were added. |
| 875 | self._order = [] |
| 876 | |
| 877 | # The last auto generated id. |
| 878 | self._last_auto_id = 0 |
| 879 | |
| 880 | # Unique ID on which to base the Content-ID headers. |
| 881 | self._base_id = None |
| 882 | |
Joe Gregorio | c752e33 | 2012-07-11 14:43:52 -0400 | [diff] [blame] | 883 | # A map from request id to (httplib2.Response, content) response pairs |
Joe Gregorio | 654f4a2 | 2012-02-09 14:15:44 -0500 | [diff] [blame] | 884 | self._responses = {} |
| 885 | |
| 886 | # A map of id(Credentials) that have been refreshed. |
| 887 | self._refreshed_credentials = {} |
| 888 | |
| 889 | def _refresh_and_apply_credentials(self, request, http): |
| 890 | """Refresh the credentials and apply to the request. |
| 891 | |
| 892 | Args: |
| 893 | request: HttpRequest, the request. |
| 894 | http: httplib2.Http, the global http object for the batch. |
| 895 | """ |
| 896 | # For the credentials to refresh, but only once per refresh_token |
| 897 | # If there is no http per the request then refresh the http passed in |
| 898 | # via execute() |
| 899 | creds = None |
| 900 | if request.http is not None and hasattr(request.http.request, |
| 901 | 'credentials'): |
| 902 | creds = request.http.request.credentials |
| 903 | elif http is not None and hasattr(http.request, 'credentials'): |
| 904 | creds = http.request.credentials |
| 905 | if creds is not None: |
| 906 | if id(creds) not in self._refreshed_credentials: |
| 907 | creds.refresh(http) |
| 908 | self._refreshed_credentials[id(creds)] = 1 |
| 909 | |
| 910 | # Only apply the credentials if we are using the http object passed in, |
| 911 | # otherwise apply() will get called during _serialize_request(). |
| 912 | if request.http is None or not hasattr(request.http.request, |
| 913 | 'credentials'): |
| 914 | creds.apply(request.headers) |
| 915 | |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 916 | def _id_to_header(self, id_): |
| 917 | """Convert an id to a Content-ID header value. |
| 918 | |
| 919 | Args: |
| 920 | id_: string, identifier of individual request. |
| 921 | |
| 922 | Returns: |
| 923 | A Content-ID header with the id_ encoded into it. A UUID is prepended to |
| 924 | the value because Content-ID headers are supposed to be universally |
| 925 | unique. |
| 926 | """ |
| 927 | if self._base_id is None: |
| 928 | self._base_id = uuid.uuid4() |
| 929 | |
| 930 | return '<%s+%s>' % (self._base_id, urllib.quote(id_)) |
| 931 | |
| 932 | def _header_to_id(self, header): |
| 933 | """Convert a Content-ID header value to an id. |
| 934 | |
| 935 | Presumes the Content-ID header conforms to the format that _id_to_header() |
| 936 | returns. |
| 937 | |
| 938 | Args: |
| 939 | header: string, Content-ID header value. |
| 940 | |
| 941 | Returns: |
| 942 | The extracted id value. |
| 943 | |
| 944 | Raises: |
| 945 | BatchError if the header is not in the expected format. |
| 946 | """ |
| 947 | if header[0] != '<' or header[-1] != '>': |
| 948 | raise BatchError("Invalid value for Content-ID: %s" % header) |
| 949 | if '+' not in header: |
| 950 | raise BatchError("Invalid value for Content-ID: %s" % header) |
| 951 | base, id_ = header[1:-1].rsplit('+', 1) |
| 952 | |
| 953 | return urllib.unquote(id_) |
| 954 | |
| 955 | def _serialize_request(self, request): |
| 956 | """Convert an HttpRequest object into a string. |
| 957 | |
| 958 | Args: |
| 959 | request: HttpRequest, the request to serialize. |
| 960 | |
| 961 | Returns: |
| 962 | The request as a string in application/http format. |
| 963 | """ |
| 964 | # Construct status line |
| 965 | parsed = urlparse.urlparse(request.uri) |
| 966 | request_line = urlparse.urlunparse( |
| 967 | (None, None, parsed.path, parsed.params, parsed.query, None) |
| 968 | ) |
| 969 | status_line = request.method + ' ' + request_line + ' HTTP/1.1\n' |
Joe Gregorio | 5d1171b | 2012-01-05 10:48:24 -0500 | [diff] [blame] | 970 | major, minor = request.headers.get('content-type', 'application/json').split('/') |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 971 | msg = MIMENonMultipart(major, minor) |
| 972 | headers = request.headers.copy() |
| 973 | |
Joe Gregorio | 654f4a2 | 2012-02-09 14:15:44 -0500 | [diff] [blame] | 974 | if request.http is not None and hasattr(request.http.request, |
| 975 | 'credentials'): |
| 976 | request.http.request.credentials.apply(headers) |
| 977 | |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 978 | # MIMENonMultipart adds its own Content-Type header. |
| 979 | if 'content-type' in headers: |
| 980 | del headers['content-type'] |
| 981 | |
| 982 | for key, value in headers.iteritems(): |
| 983 | msg[key] = value |
| 984 | msg['Host'] = parsed.netloc |
| 985 | msg.set_unixfrom(None) |
| 986 | |
| 987 | if request.body is not None: |
| 988 | msg.set_payload(request.body) |
Joe Gregorio | 5d1171b | 2012-01-05 10:48:24 -0500 | [diff] [blame] | 989 | msg['content-length'] = str(len(request.body)) |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 990 | |
Joe Gregorio | 654f4a2 | 2012-02-09 14:15:44 -0500 | [diff] [blame] | 991 | # Serialize the mime message. |
| 992 | fp = StringIO.StringIO() |
| 993 | # maxheaderlen=0 means don't line wrap headers. |
| 994 | g = Generator(fp, maxheaderlen=0) |
| 995 | g.flatten(msg, unixfrom=False) |
| 996 | body = fp.getvalue() |
| 997 | |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 998 | # Strip off the \n\n that the MIME lib tacks onto the end of the payload. |
| 999 | if request.body is None: |
| 1000 | body = body[:-2] |
| 1001 | |
Joe Gregorio | dd81382 | 2012-01-25 10:32:47 -0500 | [diff] [blame] | 1002 | return status_line.encode('utf-8') + body |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 1003 | |
| 1004 | def _deserialize_response(self, payload): |
| 1005 | """Convert string into httplib2 response and content. |
| 1006 | |
| 1007 | Args: |
| 1008 | payload: string, headers and body as a string. |
| 1009 | |
| 1010 | Returns: |
Joe Gregorio | c752e33 | 2012-07-11 14:43:52 -0400 | [diff] [blame] | 1011 | A pair (resp, content), such as would be returned from httplib2.request. |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 1012 | """ |
| 1013 | # Strip off the status line |
| 1014 | status_line, payload = payload.split('\n', 1) |
Joe Gregorio | 5d1171b | 2012-01-05 10:48:24 -0500 | [diff] [blame] | 1015 | protocol, status, reason = status_line.split(' ', 2) |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 1016 | |
| 1017 | # Parse the rest of the response |
| 1018 | parser = FeedParser() |
| 1019 | parser.feed(payload) |
| 1020 | msg = parser.close() |
| 1021 | msg['status'] = status |
| 1022 | |
| 1023 | # Create httplib2.Response from the parsed headers. |
| 1024 | resp = httplib2.Response(msg) |
| 1025 | resp.reason = reason |
| 1026 | resp.version = int(protocol.split('/', 1)[1].replace('.', '')) |
| 1027 | |
| 1028 | content = payload.split('\r\n\r\n', 1)[1] |
| 1029 | |
| 1030 | return resp, content |
| 1031 | |
| 1032 | def _new_id(self): |
| 1033 | """Create a new id. |
| 1034 | |
| 1035 | Auto incrementing number that avoids conflicts with ids already used. |
| 1036 | |
| 1037 | Returns: |
| 1038 | string, a new unique id. |
| 1039 | """ |
| 1040 | self._last_auto_id += 1 |
| 1041 | while str(self._last_auto_id) in self._requests: |
| 1042 | self._last_auto_id += 1 |
| 1043 | return str(self._last_auto_id) |
| 1044 | |
| 1045 | def add(self, request, callback=None, request_id=None): |
| 1046 | """Add a new request. |
| 1047 | |
| 1048 | Every callback added will be paired with a unique id, the request_id. That |
| 1049 | unique id will be passed back to the callback when the response comes back |
| 1050 | from the server. The default behavior is to have the library generate it's |
| 1051 | own unique id. If the caller passes in a request_id then they must ensure |
| 1052 | uniqueness for each request_id, and if they are not an exception is |
| 1053 | raised. Callers should either supply all request_ids or nevery supply a |
| 1054 | request id, to avoid such an error. |
| 1055 | |
| 1056 | Args: |
| 1057 | request: HttpRequest, Request to add to the batch. |
| 1058 | callback: callable, A callback to be called for this response, of the |
Joe Gregorio | 4fbde1c | 2012-07-11 14:47:39 -0400 | [diff] [blame] | 1059 | form callback(id, response, exception). The first parameter is the |
| 1060 | request id, and the second is the deserialized response object. The |
| 1061 | third is an apiclient.errors.HttpError exception object if an HTTP error |
| 1062 | occurred while processing the request, or None if no errors occurred. |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 1063 | request_id: string, A unique id for the request. The id will be passed to |
| 1064 | the callback with the response. |
| 1065 | |
| 1066 | Returns: |
| 1067 | None |
| 1068 | |
| 1069 | Raises: |
Joe Gregorio | ebd0b84 | 2012-06-15 14:14:17 -0400 | [diff] [blame] | 1070 | BatchError if a media request is added to a batch. |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 1071 | KeyError is the request_id is not unique. |
| 1072 | """ |
| 1073 | if request_id is None: |
| 1074 | request_id = self._new_id() |
| 1075 | if request.resumable is not None: |
Joe Gregorio | ebd0b84 | 2012-06-15 14:14:17 -0400 | [diff] [blame] | 1076 | raise BatchError("Media requests cannot be used in a batch request.") |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 1077 | if request_id in self._requests: |
| 1078 | raise KeyError("A request with this ID already exists: %s" % request_id) |
Joe Gregorio | 654f4a2 | 2012-02-09 14:15:44 -0500 | [diff] [blame] | 1079 | self._requests[request_id] = request |
| 1080 | self._callbacks[request_id] = callback |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 1081 | self._order.append(request_id) |
| 1082 | |
Joe Gregorio | 654f4a2 | 2012-02-09 14:15:44 -0500 | [diff] [blame] | 1083 | def _execute(self, http, order, requests): |
| 1084 | """Serialize batch request, send to server, process response. |
| 1085 | |
| 1086 | Args: |
| 1087 | http: httplib2.Http, an http object to be used to make the request with. |
| 1088 | order: list, list of request ids in the order they were added to the |
| 1089 | batch. |
| 1090 | request: list, list of request objects to send. |
| 1091 | |
| 1092 | Raises: |
Joe Gregorio | 77af30a | 2012-08-01 14:54:40 -0400 | [diff] [blame] | 1093 | httplib2.HttpLib2Error if a transport error has occured. |
Joe Gregorio | 654f4a2 | 2012-02-09 14:15:44 -0500 | [diff] [blame] | 1094 | apiclient.errors.BatchError if the response is the wrong format. |
| 1095 | """ |
| 1096 | message = MIMEMultipart('mixed') |
| 1097 | # Message should not write out it's own headers. |
| 1098 | setattr(message, '_write_headers', lambda self: None) |
| 1099 | |
| 1100 | # Add all the individual requests. |
| 1101 | for request_id in order: |
| 1102 | request = requests[request_id] |
| 1103 | |
| 1104 | msg = MIMENonMultipart('application', 'http') |
| 1105 | msg['Content-Transfer-Encoding'] = 'binary' |
| 1106 | msg['Content-ID'] = self._id_to_header(request_id) |
| 1107 | |
| 1108 | body = self._serialize_request(request) |
| 1109 | msg.set_payload(body) |
| 1110 | message.attach(msg) |
| 1111 | |
| 1112 | body = message.as_string() |
| 1113 | |
| 1114 | headers = {} |
| 1115 | headers['content-type'] = ('multipart/mixed; ' |
| 1116 | 'boundary="%s"') % message.get_boundary() |
| 1117 | |
| 1118 | resp, content = http.request(self._batch_uri, 'POST', body=body, |
| 1119 | headers=headers) |
| 1120 | |
| 1121 | if resp.status >= 300: |
| 1122 | raise HttpError(resp, content, self._batch_uri) |
| 1123 | |
| 1124 | # Now break out the individual responses and store each one. |
| 1125 | boundary, _ = content.split(None, 1) |
| 1126 | |
| 1127 | # Prepend with a content-type header so FeedParser can handle it. |
| 1128 | header = 'content-type: %s\r\n\r\n' % resp['content-type'] |
| 1129 | for_parser = header + content |
| 1130 | |
| 1131 | parser = FeedParser() |
| 1132 | parser.feed(for_parser) |
| 1133 | mime_response = parser.close() |
| 1134 | |
| 1135 | if not mime_response.is_multipart(): |
| 1136 | raise BatchError("Response not in multipart/mixed format.", resp, |
| 1137 | content) |
| 1138 | |
| 1139 | for part in mime_response.get_payload(): |
| 1140 | request_id = self._header_to_id(part['Content-ID']) |
Joe Gregorio | c752e33 | 2012-07-11 14:43:52 -0400 | [diff] [blame] | 1141 | response, content = self._deserialize_response(part.get_payload()) |
| 1142 | self._responses[request_id] = (response, content) |
Joe Gregorio | 654f4a2 | 2012-02-09 14:15:44 -0500 | [diff] [blame] | 1143 | |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 1144 | def execute(self, http=None): |
| 1145 | """Execute all the requests as a single batched HTTP request. |
| 1146 | |
| 1147 | Args: |
| 1148 | http: httplib2.Http, an http object to be used in place of the one the |
| 1149 | HttpRequest request object was constructed with. If one isn't supplied |
| 1150 | then use a http object from the requests in this batch. |
| 1151 | |
| 1152 | Returns: |
| 1153 | None |
| 1154 | |
| 1155 | Raises: |
Joe Gregorio | 77af30a | 2012-08-01 14:54:40 -0400 | [diff] [blame] | 1156 | httplib2.HttpLib2Error if a transport error has occured. |
Joe Gregorio | 5d1171b | 2012-01-05 10:48:24 -0500 | [diff] [blame] | 1157 | apiclient.errors.BatchError if the response is the wrong format. |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 1158 | """ |
Joe Gregorio | 654f4a2 | 2012-02-09 14:15:44 -0500 | [diff] [blame] | 1159 | |
| 1160 | # If http is not supplied use the first valid one given in the requests. |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 1161 | if http is None: |
| 1162 | for request_id in self._order: |
Joe Gregorio | 654f4a2 | 2012-02-09 14:15:44 -0500 | [diff] [blame] | 1163 | request = self._requests[request_id] |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 1164 | if request is not None: |
| 1165 | http = request.http |
| 1166 | break |
Joe Gregorio | 654f4a2 | 2012-02-09 14:15:44 -0500 | [diff] [blame] | 1167 | |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 1168 | if http is None: |
| 1169 | raise ValueError("Missing a valid http object.") |
| 1170 | |
Joe Gregorio | 654f4a2 | 2012-02-09 14:15:44 -0500 | [diff] [blame] | 1171 | self._execute(http, self._order, self._requests) |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 1172 | |
Joe Gregorio | 654f4a2 | 2012-02-09 14:15:44 -0500 | [diff] [blame] | 1173 | # Loop over all the requests and check for 401s. For each 401 request the |
| 1174 | # credentials should be refreshed and then sent again in a separate batch. |
| 1175 | redo_requests = {} |
| 1176 | redo_order = [] |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 1177 | |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 1178 | for request_id in self._order: |
Joe Gregorio | c752e33 | 2012-07-11 14:43:52 -0400 | [diff] [blame] | 1179 | resp, content = self._responses[request_id] |
| 1180 | if resp['status'] == '401': |
Joe Gregorio | 654f4a2 | 2012-02-09 14:15:44 -0500 | [diff] [blame] | 1181 | redo_order.append(request_id) |
| 1182 | request = self._requests[request_id] |
| 1183 | self._refresh_and_apply_credentials(request, http) |
| 1184 | redo_requests[request_id] = request |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 1185 | |
Joe Gregorio | 654f4a2 | 2012-02-09 14:15:44 -0500 | [diff] [blame] | 1186 | if redo_requests: |
| 1187 | self._execute(http, redo_order, redo_requests) |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 1188 | |
Joe Gregorio | 654f4a2 | 2012-02-09 14:15:44 -0500 | [diff] [blame] | 1189 | # Now process all callbacks that are erroring, and raise an exception for |
| 1190 | # ones that return a non-2xx response? Or add extra parameter to callback |
| 1191 | # that contains an HttpError? |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 1192 | |
Joe Gregorio | 654f4a2 | 2012-02-09 14:15:44 -0500 | [diff] [blame] | 1193 | for request_id in self._order: |
Joe Gregorio | c752e33 | 2012-07-11 14:43:52 -0400 | [diff] [blame] | 1194 | resp, content = self._responses[request_id] |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 1195 | |
Joe Gregorio | 654f4a2 | 2012-02-09 14:15:44 -0500 | [diff] [blame] | 1196 | request = self._requests[request_id] |
| 1197 | callback = self._callbacks[request_id] |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 1198 | |
Joe Gregorio | 654f4a2 | 2012-02-09 14:15:44 -0500 | [diff] [blame] | 1199 | response = None |
| 1200 | exception = None |
| 1201 | try: |
Joe Gregorio | 3fb9367 | 2012-07-25 11:31:11 -0400 | [diff] [blame] | 1202 | if resp.status >= 300: |
| 1203 | raise HttpError(resp, content, request.uri) |
Joe Gregorio | c752e33 | 2012-07-11 14:43:52 -0400 | [diff] [blame] | 1204 | response = request.postproc(resp, content) |
Joe Gregorio | 654f4a2 | 2012-02-09 14:15:44 -0500 | [diff] [blame] | 1205 | except HttpError, e: |
| 1206 | exception = e |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 1207 | |
Joe Gregorio | 654f4a2 | 2012-02-09 14:15:44 -0500 | [diff] [blame] | 1208 | if callback is not None: |
| 1209 | callback(request_id, response, exception) |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 1210 | if self._callback is not None: |
Joe Gregorio | 654f4a2 | 2012-02-09 14:15:44 -0500 | [diff] [blame] | 1211 | self._callback(request_id, response, exception) |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 1212 | |
| 1213 | |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 1214 | class HttpRequestMock(object): |
| 1215 | """Mock of HttpRequest. |
| 1216 | |
| 1217 | Do not construct directly, instead use RequestMockBuilder. |
| 1218 | """ |
| 1219 | |
| 1220 | def __init__(self, resp, content, postproc): |
| 1221 | """Constructor for HttpRequestMock |
| 1222 | |
| 1223 | Args: |
| 1224 | resp: httplib2.Response, the response to emulate coming from the request |
| 1225 | content: string, the response body |
| 1226 | postproc: callable, the post processing function usually supplied by |
| 1227 | the model class. See model.JsonModel.response() as an example. |
| 1228 | """ |
| 1229 | self.resp = resp |
| 1230 | self.content = content |
| 1231 | self.postproc = postproc |
| 1232 | if resp is None: |
Joe Gregorio | c672246 | 2010-12-20 14:29:28 -0500 | [diff] [blame] | 1233 | self.resp = httplib2.Response({'status': 200, 'reason': 'OK'}) |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 1234 | if 'reason' in self.resp: |
| 1235 | self.resp.reason = self.resp['reason'] |
| 1236 | |
| 1237 | def execute(self, http=None): |
| 1238 | """Execute the request. |
| 1239 | |
| 1240 | Same behavior as HttpRequest.execute(), but the response is |
| 1241 | mocked and not really from an HTTP request/response. |
| 1242 | """ |
| 1243 | return self.postproc(self.resp, self.content) |
| 1244 | |
| 1245 | |
| 1246 | class RequestMockBuilder(object): |
| 1247 | """A simple mock of HttpRequest |
| 1248 | |
| 1249 | Pass in a dictionary to the constructor that maps request methodIds to |
Joe Gregorio | a388ce3 | 2011-09-09 17:19:13 -0400 | [diff] [blame] | 1250 | tuples of (httplib2.Response, content, opt_expected_body) that should be |
| 1251 | returned when that method is called. None may also be passed in for the |
| 1252 | httplib2.Response, in which case a 200 OK response will be generated. |
| 1253 | If an opt_expected_body (str or dict) is provided, it will be compared to |
| 1254 | the body and UnexpectedBodyError will be raised on inequality. |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 1255 | |
| 1256 | Example: |
| 1257 | response = '{"data": {"id": "tag:google.c...' |
| 1258 | requestBuilder = RequestMockBuilder( |
| 1259 | { |
Joe Gregorio | c4fc095 | 2011-11-09 12:21:11 -0500 | [diff] [blame] | 1260 | 'plus.activities.get': (None, response), |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 1261 | } |
| 1262 | ) |
Joe Gregorio | c4fc095 | 2011-11-09 12:21:11 -0500 | [diff] [blame] | 1263 | apiclient.discovery.build("plus", "v1", requestBuilder=requestBuilder) |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 1264 | |
| 1265 | Methods that you do not supply a response for will return a |
Joe Gregorio | 66f5752 | 2011-11-30 11:00:00 -0500 | [diff] [blame] | 1266 | 200 OK with an empty string as the response content or raise an excpetion |
| 1267 | if check_unexpected is set to True. The methodId is taken from the rpcName |
Joe Gregorio | a388ce3 | 2011-09-09 17:19:13 -0400 | [diff] [blame] | 1268 | in the discovery document. |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 1269 | |
| 1270 | For more details see the project wiki. |
| 1271 | """ |
| 1272 | |
Joe Gregorio | a388ce3 | 2011-09-09 17:19:13 -0400 | [diff] [blame] | 1273 | def __init__(self, responses, check_unexpected=False): |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 1274 | """Constructor for RequestMockBuilder |
| 1275 | |
| 1276 | The constructed object should be a callable object |
| 1277 | that can replace the class HttpResponse. |
| 1278 | |
| 1279 | responses - A dictionary that maps methodIds into tuples |
| 1280 | of (httplib2.Response, content). The methodId |
| 1281 | comes from the 'rpcName' field in the discovery |
| 1282 | document. |
Joe Gregorio | a388ce3 | 2011-09-09 17:19:13 -0400 | [diff] [blame] | 1283 | check_unexpected - A boolean setting whether or not UnexpectedMethodError |
| 1284 | should be raised on unsupplied method. |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 1285 | """ |
| 1286 | self.responses = responses |
Joe Gregorio | a388ce3 | 2011-09-09 17:19:13 -0400 | [diff] [blame] | 1287 | self.check_unexpected = check_unexpected |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 1288 | |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 1289 | def __call__(self, http, postproc, uri, method='GET', body=None, |
Joe Gregorio | d0bd388 | 2011-11-22 09:49:47 -0500 | [diff] [blame] | 1290 | headers=None, methodId=None, resumable=None): |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 1291 | """Implements the callable interface that discovery.build() expects |
| 1292 | of requestBuilder, which is to build an object compatible with |
| 1293 | HttpRequest.execute(). See that method for the description of the |
| 1294 | parameters and the expected response. |
| 1295 | """ |
| 1296 | if methodId in self.responses: |
Joe Gregorio | a388ce3 | 2011-09-09 17:19:13 -0400 | [diff] [blame] | 1297 | response = self.responses[methodId] |
| 1298 | resp, content = response[:2] |
| 1299 | if len(response) > 2: |
| 1300 | # Test the body against the supplied expected_body. |
| 1301 | expected_body = response[2] |
| 1302 | if bool(expected_body) != bool(body): |
| 1303 | # Not expecting a body and provided one |
| 1304 | # or expecting a body and not provided one. |
| 1305 | raise UnexpectedBodyError(expected_body, body) |
| 1306 | if isinstance(expected_body, str): |
| 1307 | expected_body = simplejson.loads(expected_body) |
| 1308 | body = simplejson.loads(body) |
| 1309 | if body != expected_body: |
| 1310 | raise UnexpectedBodyError(expected_body, body) |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 1311 | return HttpRequestMock(resp, content, postproc) |
Joe Gregorio | a388ce3 | 2011-09-09 17:19:13 -0400 | [diff] [blame] | 1312 | elif self.check_unexpected: |
| 1313 | raise UnexpectedMethodError(methodId) |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 1314 | else: |
Joe Gregorio | d433b2a | 2011-02-22 10:51:51 -0500 | [diff] [blame] | 1315 | model = JsonModel(False) |
Joe Gregorio | af276d2 | 2010-12-09 14:26:58 -0500 | [diff] [blame] | 1316 | return HttpRequestMock(None, '{}', model.response) |
Joe Gregorio | cb8103d | 2011-02-11 23:20:52 -0500 | [diff] [blame] | 1317 | |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 1318 | |
Joe Gregorio | cb8103d | 2011-02-11 23:20:52 -0500 | [diff] [blame] | 1319 | class HttpMock(object): |
| 1320 | """Mock of httplib2.Http""" |
| 1321 | |
Joe Gregorio | ec34365 | 2011-02-16 16:52:51 -0500 | [diff] [blame] | 1322 | def __init__(self, filename, headers=None): |
Joe Gregorio | cb8103d | 2011-02-11 23:20:52 -0500 | [diff] [blame] | 1323 | """ |
| 1324 | Args: |
| 1325 | filename: string, absolute filename to read response from |
| 1326 | headers: dict, header to return with response |
| 1327 | """ |
Joe Gregorio | ec34365 | 2011-02-16 16:52:51 -0500 | [diff] [blame] | 1328 | if headers is None: |
| 1329 | headers = {'status': '200 OK'} |
Joe Gregorio | cb8103d | 2011-02-11 23:20:52 -0500 | [diff] [blame] | 1330 | f = file(filename, 'r') |
| 1331 | self.data = f.read() |
| 1332 | f.close() |
| 1333 | self.headers = headers |
| 1334 | |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 1335 | def request(self, uri, |
Joe Gregorio | 7c22ab2 | 2011-02-16 15:32:39 -0500 | [diff] [blame] | 1336 | method='GET', |
Joe Gregorio | deeb020 | 2011-02-15 14:49:57 -0500 | [diff] [blame] | 1337 | body=None, |
| 1338 | headers=None, |
| 1339 | redirections=1, |
| 1340 | connection_type=None): |
Joe Gregorio | cb8103d | 2011-02-11 23:20:52 -0500 | [diff] [blame] | 1341 | return httplib2.Response(self.headers), self.data |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 1342 | |
| 1343 | |
| 1344 | class HttpMockSequence(object): |
| 1345 | """Mock of httplib2.Http |
| 1346 | |
| 1347 | Mocks a sequence of calls to request returning different responses for each |
| 1348 | call. Create an instance initialized with the desired response headers |
| 1349 | and content and then use as if an httplib2.Http instance. |
| 1350 | |
| 1351 | http = HttpMockSequence([ |
| 1352 | ({'status': '401'}, ''), |
| 1353 | ({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'), |
| 1354 | ({'status': '200'}, 'echo_request_headers'), |
| 1355 | ]) |
| 1356 | resp, content = http.request("http://examples.com") |
| 1357 | |
| 1358 | There are special values you can pass in for content to trigger |
| 1359 | behavours that are helpful in testing. |
| 1360 | |
| 1361 | 'echo_request_headers' means return the request headers in the response body |
Joe Gregorio | e9e236f | 2011-03-21 22:23:14 -0400 | [diff] [blame] | 1362 | 'echo_request_headers_as_json' means return the request headers in |
| 1363 | the response body |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 1364 | 'echo_request_body' means return the request body in the response body |
Joe Gregorio | 0bc7091 | 2011-05-24 15:30:49 -0400 | [diff] [blame] | 1365 | 'echo_request_uri' means return the request uri in the response body |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 1366 | """ |
| 1367 | |
| 1368 | def __init__(self, iterable): |
| 1369 | """ |
| 1370 | Args: |
| 1371 | iterable: iterable, a sequence of pairs of (headers, body) |
| 1372 | """ |
| 1373 | self._iterable = iterable |
Joe Gregorio | 708388c | 2012-06-15 13:43:04 -0400 | [diff] [blame] | 1374 | self.follow_redirects = True |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 1375 | |
| 1376 | def request(self, uri, |
| 1377 | method='GET', |
| 1378 | body=None, |
| 1379 | headers=None, |
| 1380 | redirections=1, |
| 1381 | connection_type=None): |
| 1382 | resp, content = self._iterable.pop(0) |
| 1383 | if content == 'echo_request_headers': |
| 1384 | content = headers |
Joe Gregorio | f415342 | 2011-03-18 22:45:18 -0400 | [diff] [blame] | 1385 | elif content == 'echo_request_headers_as_json': |
| 1386 | content = simplejson.dumps(headers) |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 1387 | elif content == 'echo_request_body': |
| 1388 | content = body |
Joe Gregorio | 0bc7091 | 2011-05-24 15:30:49 -0400 | [diff] [blame] | 1389 | elif content == 'echo_request_uri': |
| 1390 | content = uri |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 1391 | return httplib2.Response(resp), content |
Joe Gregorio | 6bcbcea | 2011-03-10 15:26:05 -0500 | [diff] [blame] | 1392 | |
| 1393 | |
| 1394 | def set_user_agent(http, user_agent): |
Joe Gregorio | f415342 | 2011-03-18 22:45:18 -0400 | [diff] [blame] | 1395 | """Set the user-agent on every request. |
| 1396 | |
Joe Gregorio | 6bcbcea | 2011-03-10 15:26:05 -0500 | [diff] [blame] | 1397 | Args: |
| 1398 | http - An instance of httplib2.Http |
| 1399 | or something that acts like it. |
| 1400 | user_agent: string, the value for the user-agent header. |
| 1401 | |
| 1402 | Returns: |
| 1403 | A modified instance of http that was passed in. |
| 1404 | |
| 1405 | Example: |
| 1406 | |
| 1407 | h = httplib2.Http() |
| 1408 | h = set_user_agent(h, "my-app-name/6.0") |
| 1409 | |
| 1410 | Most of the time the user-agent will be set doing auth, this is for the rare |
| 1411 | cases where you are accessing an unauthenticated endpoint. |
| 1412 | """ |
| 1413 | request_orig = http.request |
| 1414 | |
| 1415 | # The closure that will replace 'httplib2.Http.request'. |
| 1416 | def new_request(uri, method='GET', body=None, headers=None, |
| 1417 | redirections=httplib2.DEFAULT_MAX_REDIRECTS, |
| 1418 | connection_type=None): |
| 1419 | """Modify the request headers to add the user-agent.""" |
| 1420 | if headers is None: |
| 1421 | headers = {} |
| 1422 | if 'user-agent' in headers: |
| 1423 | headers['user-agent'] = user_agent + ' ' + headers['user-agent'] |
| 1424 | else: |
| 1425 | headers['user-agent'] = user_agent |
| 1426 | resp, content = request_orig(uri, method, body, headers, |
| 1427 | redirections, connection_type) |
| 1428 | return resp, content |
| 1429 | |
| 1430 | http.request = new_request |
| 1431 | return http |
Joe Gregorio | f415342 | 2011-03-18 22:45:18 -0400 | [diff] [blame] | 1432 | |
| 1433 | |
| 1434 | def tunnel_patch(http): |
| 1435 | """Tunnel PATCH requests over POST. |
| 1436 | Args: |
| 1437 | http - An instance of httplib2.Http |
| 1438 | or something that acts like it. |
| 1439 | |
| 1440 | Returns: |
| 1441 | A modified instance of http that was passed in. |
| 1442 | |
| 1443 | Example: |
| 1444 | |
| 1445 | h = httplib2.Http() |
| 1446 | h = tunnel_patch(h, "my-app-name/6.0") |
| 1447 | |
| 1448 | Useful if you are running on a platform that doesn't support PATCH. |
| 1449 | Apply this last if you are using OAuth 1.0, as changing the method |
| 1450 | will result in a different signature. |
| 1451 | """ |
| 1452 | request_orig = http.request |
| 1453 | |
| 1454 | # The closure that will replace 'httplib2.Http.request'. |
| 1455 | def new_request(uri, method='GET', body=None, headers=None, |
| 1456 | redirections=httplib2.DEFAULT_MAX_REDIRECTS, |
| 1457 | connection_type=None): |
| 1458 | """Modify the request headers to add the user-agent.""" |
| 1459 | if headers is None: |
| 1460 | headers = {} |
| 1461 | if method == 'PATCH': |
Joe Gregorio | 06d852b | 2011-03-25 15:03:10 -0400 | [diff] [blame] | 1462 | if 'oauth_token' in headers.get('authorization', ''): |
Joe Gregorio | e9e236f | 2011-03-21 22:23:14 -0400 | [diff] [blame] | 1463 | logging.warning( |
Joe Gregorio | 06d852b | 2011-03-25 15:03:10 -0400 | [diff] [blame] | 1464 | 'OAuth 1.0 request made with Credentials after tunnel_patch.') |
Joe Gregorio | f415342 | 2011-03-18 22:45:18 -0400 | [diff] [blame] | 1465 | headers['x-http-method-override'] = "PATCH" |
| 1466 | method = 'POST' |
| 1467 | resp, content = request_orig(uri, method, body, headers, |
| 1468 | redirections, connection_type) |
| 1469 | return resp, content |
| 1470 | |
| 1471 | http.request = new_request |
| 1472 | return http |