tarina

git clone https://git.tarina.org/tarina
Log | Files | Refs | README | LICENSE

upload_video.py (1561B)


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