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