upload_video.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import time
  2. import random
  3. import httplib
  4. import apiclient.http
  5. import httplib2
  6. from googleapiclient.errors import ResumableUploadError
  7. import lib
  8. RETRIABLE_EXCEPTIONS = [
  9. httplib2.HttpLib2Error, IOError, httplib.NotConnected,
  10. httplib.IncompleteRead, httplib.ImproperConnectionState,
  11. httplib.CannotSendRequest, httplib.CannotSendHeader,
  12. httplib.ResponseNotReady, httplib.BadStatusLine,
  13. ResumableUploadError
  14. ]
  15. def _upload_to_request(request, progress_callback):
  16. """Upload a video to a Youtube request. Return video ID."""
  17. while 1:
  18. status, response = request.next_chunk()
  19. if response:
  20. if "id" in response:
  21. return response['id']
  22. else:
  23. raise KeyError("The response has no 'id' field")
  24. elif status and progress_callback:
  25. progress_callback(status.total_size, status.resumable_progress)
  26. def upload(resource, path, body, chunksize=int(1e6), progress_callback=None):
  27. """Upload video to Youtube. Return video ID."""
  28. body_keys = ",".join(body.keys())
  29. media = apiclient.http.MediaFileUpload(path, chunksize=chunksize,
  30. resumable=True, mimetype="application/octet-stream")
  31. request = resource.videos().insert(part=body_keys, body=body, media_body=media)
  32. upload_fun = lambda: _upload_to_request(request, progress_callback)
  33. return lib.retriable_exceptions(upload_fun, RETRIABLE_EXCEPTIONS, max_retries=10)