I’m working with Google Drive API and running into an issue where my OAuth2 tokens expire after about a week. Every time this happens, I have to manually go through the browser authentication flow again to get new credentials. This is really annoying for an automated script that should run without any user input. Is there some way to handle this token refresh automatically so I don’t have to babysit it every few days?
import os
import json
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
# Required permissions for Drive access
PERMISSIONS = ['https://www.googleapis.com/auth/drive.metadata.readonly']
def authenticate_drive():
"""Handles authentication for Google Drive API access.
Returns a service object for making API calls.
"""
user_creds = None
# Check if we have stored credentials
if os.path.exists('stored_creds.json'):
user_creds = Credentials.from_authorized_user_file('stored_creds.json', PERMISSIONS)
# Handle expired or missing credentials
if not user_creds or not user_creds.valid:
if user_creds and user_creds.expired and user_creds.refresh_token:
user_creds.refresh(Request())
else:
auth_flow = InstalledAppFlow.from_client_secrets_file(
'client_secret.json', PERMISSIONS)
user_creds = auth_flow.run_local_server(port=8080)
# Store credentials for future use
with open('stored_creds.json', 'w') as cred_file:
cred_file.write(user_creds.to_json())
return build('drive', 'v3', credentials=user_creds)
def list_recent_files():
"""Fetches and displays recent files from Drive."""
drive_service = authenticate_drive()
print('Fetching recent files from Drive...')
file_list = drive_service.files().list(
pageSize=5,
fields="nextPageToken, files(id, name, modifiedTime)"
).execute()
files = file_list.get('files', [])
if not files:
print('No files found in Drive.')
return
for file_item in files:
print(f"File: {file_item['name']} (ID: {file_item['id']})")
if __name__ == '__main__':
list_recent_files()