upload_4.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. def transmit_next_chunk(self, transport):
  2. """Transmit the next chunk of the resource to be uploaded.
  3. If the current upload was initiated with ``stream_final=False``,
  4. this method will dynamically determine if the upload has completed.
  5. The upload will be considered complete if the stream produces
  6. fewer than :attr:`chunk_size` bytes when a chunk is read from it.
  7. In the case of failure, an exception is thrown that preserves the
  8. failed response:
  9. .. testsetup:: bad-response
  10. import io
  11. import mock
  12. import requests
  13. from six.moves import http_client
  14. from google import resumable_media
  15. import google.resumable_media.requests.upload as upload_mod
  16. transport = mock.Mock(spec=[u'request'])
  17. fake_response = requests.Response()
  18. fake_response.status_code = int(http_client.BAD_REQUEST)
  19. transport.request.return_value = fake_response
  20. upload_url = u'http://test.invalid'
  21. upload = upload_mod.ResumableUpload(
  22. upload_url, resumable_media.UPLOAD_CHUNK_SIZE)
  23. # Fake that the upload has been initiate()-d
  24. data = b'data is here'
  25. upload._stream = io.BytesIO(data)
  26. upload._total_bytes = len(data)
  27. upload._resumable_url = u'http://test.invalid?upload_id=nope'
  28. .. doctest:: bad-response
  29. :options: +NORMALIZE_WHITESPACE
  30. >>> error = None
  31. >>> try:
  32. ... upload.transmit_next_chunk(transport)
  33. ... except resumable_media.InvalidResponse as caught_exc:
  34. ... error = caught_exc
  35. ...
  36. >>> error
  37. InvalidResponse('Request failed with status code', 400,
  38. 'Expected one of', <HTTPStatus.OK: 200>, 308)
  39. >>> error.response
  40. <Response [400]>
  41. Args:
  42. transport (~requests.Session): A ``requests`` object which can
  43. make authenticated requests.
  44. Returns:
  45. ~requests.Response: The HTTP response returned by ``transport``.
  46. Raises:
  47. ~google.resumable_media.common.InvalidResponse: If the status
  48. code is not 200 or 308.
  49. """
  50. method, url, payload, headers = self._prepare_request()
  51. result = _helpers.http_request(
  52. transport, method, url, data=payload, headers=headers,
  53. retry_strategy=self._retry_strategy)
  54. self._process_response(result, len(payload))
  55. return result