upload_video.py 1.5 KB

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