PYTHON   43

upload video py

Guest on 25th August 2022 04:46:02 AM

  1. #!/usr/bin/python
  2.  
  3. import httplib
  4. import httplib2
  5. import os
  6. import random
  7. import sys
  8. import time
  9.  
  10. from apiclient.discovery import build
  11. from apiclient.errors import HttpError
  12. from apiclient.http import MediaFileUpload
  13. from oauth2client.file import Storage
  14. from oauth2client.client import flow_from_clientsecrets
  15. from oauth2client.tools import run
  16. from optparse import OptionParser
  17.  
  18.  
  19. # Explicitly tell the underlying HTTP transport library not to retry, since
  20. # we are handling retry logic ourselves.
  21. httplib2.RETRIES = 1
  22.  
  23. # Maximum number of times to retry before giving up.
  24. MAX_RETRIES = 10
  25.  
  26. # Always retry when these exceptions are raised.
  27. RETRIABLE_EXCEPTIONS = (httplib2.HttpLib2Error, IOError, httplib.NotConnected,
  28.   httplib.IncompleteRead, httplib.ImproperConnectionState,
  29.   httplib.CannotSendRequest, httplib.CannotSendHeader,
  30.   httplib.ResponseNotReady, httplib.BadStatusLine)
  31.  
  32. # Always retry when an apiclient.errors.HttpError with one of these status
  33. # codes is raised.
  34. RETRIABLE_STATUS_CODES = [500, 502, 503, 504]
  35.  
  36. # CLIENT_SECRETS_FILE, name of a file containing the OAuth 2.0 information for
  37. # this application, including client_id and client_secret. You can acquire an
  38. # ID/secret pair from the API Access tab on the Google APIs Console
  39. #   http://code.google.com/apis/console#access
  40. # For more information about using OAuth2 to access Google APIs, please visit:
  41. #   https://developers.google.com/accounts/docs/OAuth2
  42. # For more information about the client_secrets.json file format, please visit:
  43. #   https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
  44. # Please ensure that you have enabled the YouTube Data API for your project.
  45. CLIENT_SECRETS_FILE = "client_secrets.json"
  46.  
  47. # A limited OAuth 2 access scope that allows for uploading files, but not other
  48. # types of account access.
  49. YOUTUBE_UPLOAD_SCOPE = "https://www.googleapis.com/auth/youtube.upload"
  50. YOUTUBE_API_SERVICE_NAME = "youtube"
  51. YOUTUBE_API_VERSION = "v3"
  52.  
  53. # Helpful message to display if the CLIENT_SECRETS_FILE is missing.
  54. MISSING_CLIENT_SECRETS_MESSAGE = """
  55. WARNING: Please configure OAuth 2.0
  56.  
  57. To make this sample run you will need to populate the client_secrets.json file
  58. found at:
  59.  
  60.   %s
  61.  
  62. with information from the APIs Console
  63. https://code.google.com/apis/console#access
  64.  
  65. For more information about the client_secrets.json file format, please visit:
  66. https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
  67. """ % os.path.abspath(os.path.join(os.path.dirname(__file__),
  68.                                    CLIENT_SECRETS_FILE))
  69.  
  70. def get_authenticated_service():
  71.   flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=YOUTUBE_UPLOAD_SCOPE,
  72.     message=MISSING_CLIENT_SECRETS_MESSAGE)
  73.  
  74.   storage = Storage("%s-oauth2.json" % sys.argv[0])
  75.   credentials = storage.get()
  76.  
  77.   if credentials is None or credentials.invalid:
  78.     credentials = run(flow, storage)
  79.  
  80.   return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
  81.     http=credentials.authorize(httplib2.Http()))
  82.  
  83.  
  84. def initialize_upload(options):
  85.   youtube = get_authenticated_service()
  86.  
  87.   tags = None
  88.   if options.keywords:
  89.     tags = options.keywords.split(",")
  90.  
  91.   insert_request = youtube.videos().insert(
  92.     part="snippet,status",
  93.     body=dict(
  94.       snippet=dict(
  95.         title=options.title,
  96.         description=options.description,
  97.         tags=tags,
  98.         categoryId=options.category
  99.       ),
  100.       status = dict(
  101.         privacyStatus=options.privacyStatus
  102.       )
  103.     ),
  104.     media_body=MediaFileUpload(options.file, chunksize=-1, resumable=True)
  105.   )
  106.  
  107.   resumable_upload(insert_request)
  108.  
  109.  
  110. def resumable_upload(insert_request):
  111.   response = None
  112.   error = None
  113.   retry = 0
  114.   while response is None:
  115.     try:
  116.       print "Uploading file..."
  117.       status, response = insert_request.next_chunk()
  118.       if 'id' in response:
  119.         print "'%s' (video id: %s) was successfully uploaded." % (
  120.           options.title, response['id'])
  121.       else:
  122.         exit("The upload failed with an unexpected response: %s" % response)
  123.     except HttpError, e:
  124.       if e.resp.status in RETRIABLE_STATUS_CODES:
  125.         error = "A retriable HTTP error %d occurred:\n%s" % (e.resp.status,
  126.                                                              e.content)
  127.       else:
  128.         raise
  129.     except RETRIABLE_EXCEPTIONS, e:
  130.       error = "A retriable error occurred: %s" % e
  131.  
  132.     if error is not None:
  133.       print error
  134.       retry += 1
  135.       if retry > MAX_RETRIES:
  136.         exit("No longer attempting to retry.")
  137.  
  138.       max_sleep = 2 ** retry
  139.       sleep_seconds = random.random() * max_sleep
  140.       print "Sleeping %f seconds and then retrying..." % sleep_seconds
  141.       time.sleep(sleep_seconds)
  142.  
  143.  
  144. if __name__ == '__main__':
  145.   parser = OptionParser()
  146.   parser.add_option("--file", dest="file", help="Video file to upload")
  147.   parser.add_option("--title", dest="title", help="Video title",
  148.     default="Test Title")
  149.   parser.add_option("--description", dest="description", help="Video description",
  150.     default="Test Description")
  151.   parser.add_option("--category", dest="category", help="Video category",
  152.     default="22")
  153.   parser.add_option("--keywords", dest="keywords",
  154.     help="Video keywords, comma separated", default="")
  155.   parser.add_option("--privacyStatus", dest="privacyStatus", help="Video privacy status",
  156.     default="unlisted")
  157.   (options, args) = parser.parse_args()
  158.  
  159.   if options.file is None or not os.path.exists(options.file):
  160.     exit("Please specify a valid file using the --file= parameter.")
  161.   else:
  162.     initialize_upload(options)

Raw Paste


Login or Register to edit or fork this paste. It's free.