Last active
December 22, 2024 09:22
-
-
Save dreamerlzl/0c8349afe9a970400d6420215194b23a to your computer and use it in GitHub Desktop.
Access Google API with Python SDK and refresh token
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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