Skip to content

Instantly share code, notes, and snippets.

@dreamerlzl
Last active December 22, 2024 09:22
Show Gist options
  • Save dreamerlzl/0c8349afe9a970400d6420215194b23a to your computer and use it in GitHub Desktop.
Save dreamerlzl/0c8349afe9a970400d6420215194b23a to your computer and use it in GitHub Desktop.
Access Google API with Python SDK and refresh token
# make sure your app is in published but not testing mode on Google Cloud Console
# refresh token will expire in 6 months then; see https://developers.google.com/identity/protocols/oauth2
# you can get a refresh token following this answer generated by Phind.com: https://www.phind.com/search?cache=esclzqazl0knyo8xouu0mf8c&source=sidebar
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import Resource, build
from google.auth.transport.requests import Request
class GoogleDriveAgent:
def __init__(
self, client_id: str, client_secret: str, token_uri: str, refresh_token: str, scopes: list[str]
):
creds = Credentials(
None,
refresh_token=refresh_token,
token_uri=token_uri,
client_id=client_id,
client_secret=client_secret,
scopes=scopes,
)
creds.refresh(Request())
self.service: Resource = build("drive", "v3", credentials=creds)
def find_file(self, filename):
"""Search for a file in Google Drive."""
results = (
self.service.files()
.list(q=f"name='{filename}' and trashed=false", fields="files(id, name)")
.execute()
)
files = results.get("files", [])
return files[0] if files else None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment