Python code that updates YouTube thumbnails every 10 minutes, fails after about an hour - do I need to use refresh tokens?

Viewed 267

So, earlier today, I started a YouTube experiment that involves updating the thumbnail image every 10 minutes. So, I based my Python code off of a code sample from the Google Developers page on youtube.thumbnails.set(): https://developers.google.com/youtube/v3/docs/thumbnails/set

My code looks like this:

def doCredentialStuff():
    global youtube
    global flow
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    # Get credentials and create an API client
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_file, scopes)
    credentials = flow.run_console(access_type='offline')
    youtube = googleapiclient.discovery.build(
        api_service_name, api_version, credentials=credentials)

def updateYTthumb(filename):
    try:
        request = youtube.thumbnails().set(
            videoId=VIDEO_ID_UPLOAD,media_body=MediaFileUpload(filename))
        response = request.execute()
        print(response)
    except Exception as exc:
        print("ERROR!!!! I got this exception: "+str(exc)+" at time "+str(time.time()))

For my purposes, I want to upload thumbnails every 10 minutes. So, I run doCredentials() only once, at the start of running the code. Then, every 10 minutes, I re-run updateYTthumb(), where it actually executes the request. (This part)

It works perfectly for anywhere from 2 to 12 iterations! (20 - 120 minutes). However, if I let it sit for long enough, it always eventually returns this error:

 [WinError 10053] An established connection was aborted by the software in your host machine

I'm not sure how to fix this:

  • Should I get a refresh token somewhere in doCredentialStuff(), and then use it during updateYTthumb()?
3 Answers

The error is saying that something on your computer interrupted the connection, here are a few things you can try:

  • Updating your google-api-python-client
  • Disabling your antivirus
  • Disabling your firewall

try using crontab to do such timely operation.

The base doc w.r.t. authorization is OAuth 2.0 for Mobile & Desktop Apps.

This doc specifies that upon the OAuth flow, you receive a short-lived access token and a long-lived refresh token.

The section Calling Google APIs specifies that with access tokens one may issue API calls that require authorization (like yours is). The section Refreshing an access token specifies that access tokens expire periodically.

Consequently, you have to trade with the API for a fresh access token each and every time the current one becomes invalid (i.e. expired), using the refresh token you received earlier (which does not expire at all -- except for when it is explicitly revoked by the user).

Related