Skip to content

Instantly share code, notes, and snippets.

@bolinfest
Created March 16, 2024 00:42
Show Gist options
  • Save bolinfest/f83a9f3d24953466f41d5604f6bed9f5 to your computer and use it in GitHub Desktop.
Save bolinfest/f83a9f3d24953466f41d5604f6bed9f5 to your computer and use it in GitHub Desktop.
import asyncio
import json
import os.path
from aiogoogle import Aiogoogle
from aiogoogle.auth.creds import ClientCreds, UserCreds
"""Basic Python script that demonstrates programmatic access to GDrive,
though the hard work is jumping through the Google Cloud Console hoops
to get a valid set of credentials to instantiate ClientCreds and UserCreds.
"""
SCOPES = [
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.readonly',
]
# This file was downloaded from the Google Cloud Console.
CLIENT_CREDENTIALS_FILE = 'gdrive-web-client1-credentials.json'
APP_TYPE = 'web'
# This file was generated by running a slightly modified version of
# https://github.com/omarryhan/aiogoogle/blob/master/examples/auth/oauth2.py
# Note that I had to configure my Project in the Google Cloud Console as follows:
#
# - I added http://localhost:8081/callback/aiogoogle under
# "Authorized redirect URIs" so that I could use it with oauth2.py.
# - I added my personal Google account as a Test User
#
# Presumably because this is a "development" project that has not been approved
# by Google, the OAuth token is only good for 24 hours, so I have to re-run
# oauth2.py to create a new one.
USER_CREDENTIALS_FILE = 'successful-oauth-dance.json'
def create_client_creds() -> ClientCreds:
credentials = os.path.join(os.path.dirname(__file__), CLIENT_CREDENTIALS_FILE)
with open(credentials, 'r') as f:
data = json.load(f)[APP_TYPE]
return ClientCreds(client_id=data['client_id'], client_secret=data['client_secret'], scopes=SCOPES)
def create_user_creds() -> UserCreds:
credentials = os.path.join(os.path.dirname(__file__), USER_CREDENTIALS_FILE)
with open(credentials, 'r') as f:
data = json.load(f)
return UserCreds(**data)
async def main():
client_creds = create_client_creds()
async with Aiogoogle(client_creds=client_creds) as aiogoogle:
full_user_creds = create_user_creds()
# As an example, list the first 10 files in Google Drive
drive_v3 = await aiogoogle.discover('drive', 'v3')
files_list = await aiogoogle.as_user(
drive_v3.files.list(pageSize=10),
user_creds=full_user_creds
)
print(json.dumps(files_list, indent=2))
if __name__ == '__main__':
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment