Using Until Expiration Time of Access Token Retrieved By googleapis for Python

Gists

When Google APIs are used with googleapis for Python, the client is obtained as follows.

creds = service_account.Credentials.from_service_account_file(service_account_credential_file, scopes=scopes)
service = build("drive", "v3", credentials=creds)

In this case, when the script is run, the access token is retrieved every time. But, the expiration time of the retrieved access token is 1 hour. Here, there might be the case that you want to use the access token until the expiration time. It is considered that effectively using the access token will lead to SDGs. In this post, I would like to introduce a sample script for using the access token until the expiration time.

The sample script is as follows.

If you want to use this script, first, please create a service account and retrieve the credential file of the service account.

Sample script

import json
from datetime import datetime, timezone
import os
import sys
import google.auth.transport.requests
from google.oauth2 import service_account
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials


service_account_credential_file = "###" # Please set the credential file of your service account.
scopes = ["https://www.googleapis.com/auth/drive.metadata.readonly"]
access_token_file = "sample_token.txt" # Access token is stored this file.


class GetCredential:
    def __writeObj(self):
        creds = service_account.Credentials.from_service_account_file(service_account_credential_file, scopes=scopes)
        request = google.auth.transport.requests.Request()
        creds.refresh(request)
        access_token = creds.token
        token_obj = {"token": access_token, "expiry": creds.expiry.replace(tzinfo=timezone.utc).timestamp()}
        f = open(access_token_file, "w")
        f.write(json.dumps(token_obj))
        return access_token

    def do(self):
        access_token = None
        if os.path.exists(access_token_file):
            f = open(access_token_file, "r")
            token_obj = json.load(f)
            access_token = token_obj.get("token", None)
            now = datetime.now(timezone.utc).timestamp()
            if int(token_obj.get("expiry", 0)) < int(now) - 5 * 60:
                access_token = self.__writeObj()

        else:
            access_token = self.__writeObj()

        if not access_token:
            print("No access token.")
            sys.exit()
        return Credentials(access_token)


service = build("drive", "v3", credentials=GetCredential().do())

# Sample for using Drive API.
res = service.files().list(pageSize=10, fields="files(name)").execute()
print(res)

In this sample script, the file list is retrieved using the retrieved access token using googleapis for Python. The flow of this script is as follows.

  1. When this script is run for the first time, the access token is retrieved from the server side with the service account, and the retrieved access token is stored in the file of access_token_file. And, the file list of Google Drive of the service account is retrieved with the access token.

  2. When this script is run, again, when the expiration time is not finished the access token is retrieved from the file of access_token_file. And, the file list of Google Drive of the service account is retrieved with the access token.

  3. When this script is run, again, when the expiration time has already finished, the access token is retrieved from the server side with the service account. And, the file list of the Google Drive of the service account is retrieved with the access token.

Reference

 Share!