Overview of PyDrive2
maingoogle-api-python-client. It is designed to simplify common Google Drive API tasks such as OAuth authentication, file management, and file listing.repository·main·Indexed 20 days ago
https://github.com/iterative/pydrive2A maintained fork of PyDrive that serves as a Python wrapper for the Google Drive API V2. It simplifies OAuth2 authentication, file management, and pagination. Key features include the GoogleDrive and GoogleDriveFile classes for uploading, downloading, and updating files and metadata, as well as GDriveFileSystem for fsspec compatibility.
google-api-python-client. It is designed to simplify common Google Drive API tasks such as OAuth authentication, file management, and file listing.To use the GDriveFileSystem which provides fsspec compatibility, install PyDrive2 with the [fsspec] extra:
pip install 'pydrive2[fsspec]'If you need the latest development features, you can install directly from the GitHub repository.
$ pip install git+https://github.com/iterative/PyDrive2.git#egg=PyDrive2To find files based on specific criteria (like name and MIME type), use drive.ListFile(query). The query parameter takes a dictionary with a 'q' key containing a Google Drive API query string. Use .GetList() on the result to get a list of GoogleDriveFile instances.
from pydrive2.drive import GoogleDrive
drive = GoogleDrive(gauth)
filename = 'file_test'
mimetype = 'image/jpeg'
# Query string using Google Drive API syntax
query = {'q': f"title = '{filename}' and mimeType='{mimetype}'"}
# Get list of files that match against the query
files = drive.ListFile(query).GetList()Service accounts are non-human accounts used for automated workloads (VMs, data centers) that don't require manual login.
To use a service account, you must provide a service_config containing the path to your service account .json key file. Note: You must share the target Google Drive folders or files with the service account's email address for it to have access.
You can pass the configuration via a dictionary to the GoogleAuth constructor.
from pydrive2.auth import GoogleAuth
from pydrive2.drive import GoogleDrive
def login_with_service_account():
# Define the settings dict to use a service account
settings = {
"client_config_backend": "service",
"service_config": {
"client_json_file_path": "service-secrets.json",
}
}
# Create instance of GoogleAuth with settings
gauth = GoogleAuth(settings=settings)
# Authenticate using ServiceAuth()
gauth.ServiceAuth()
return gauthPyDrive2 provides a Pythonic way to handle pagination. Instead of calling .GetList(), you can iterate directly over the object returned by drive.ListFile().
By specifying the maxResults parameter in the dictionary passed to ListFile(), you control how many files are retrieved in each batch. Each iteration of the outer loop yields a list (a batch) of GoogleDriveFile objects up to the maxResults limit.
# Paginate file lists by specifying maxResults
# This example iterates through trashed files in batches of 10
for file_list in drive.ListFile({'q': 'trashed=true', 'maxResults': 10}):
print('Received %s files from Files.list()' % len(file_list)) # <= 10
for file1 in file_list:
print('title: %s, id: %s' % (file1['title'], file1['id']))PyDrive2 simplifies OAuth2.0 authentication. To set up authentication:
http://localhost:8080/ to 'Authorized redirect URIs'.client_secrets.json.client_secrets.json in your working directory.GoogleAuth and LocalWebserverAuth() to trigger the authentication flow in your browser.from pydrive2.auth import GoogleAuth
gauth = GoogleAuth()
gauth.LocalWebserverAuth() # Creates local webserver and auto handles authentication.To use OAuth2.0, download client_secrets.json from the Google API Console. You can then initialize authentication using GoogleAuth and LocalWebserverAuth. For more complex configurations, you can use a settings.yaml file to customize OAuth behavior.
from pydrive2.auth import GoogleAuth
from pydrive2.drive import GoogleDrive
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)PyDrive2 simplifies file listing and pagination.
.GetList() on a ListFile object returns an iterator that automatically handles pagination to fetch all matching files.maxResults key to ListFile and iterating over the resulting list objects.# Auto-iterate through all files matching a query
file_list = drive.ListFile({'q': "'root' in parents"}).GetList()
for file1 in file_list:
print('title: {}, id: {}'.format(file1['title'], file1['id']))
# Paginate by specifying max results
for file_list in drive.ListFile({'maxResults': 10}):
print('Received {} files'.format(len(file_list)))
for file1 in file_list:
print(file1['title'])You can install the stable version of PyDrive2 using the standard pip package manager.
$ pip install PyDrive2To download file content, use the following methods on a GoogleDriveFile instance:
GetContentFile(filename): Downloads the content and saves it to the specified local filename.GetContentString(): Retrieves the content as a string.Advanced Tip: When downloading files that might contain a Byte Order Mark (BOM), such as Google Docs exported as text, you can use the remove_bom=True parameter in GetContentString() or GetContentFile() to prevent parsing errors.
# Download file as a local file
file6 = drive.CreateFile({'id': file5['id']})
file6.GetContentFile('catlove.png')
# Download content as a string
file7 = drive.CreateFile({'id': file4['id']})
content = file7.GetContentString()
# Advanced: Remove BOM if necessary
content = file7.GetContentString(remove_bom=True)If you need to integrate Drive API into an existing website or custom UI, you can manually manage the OAuth flow using GetAuthUrl() and Auth(code):
gauth.GetAuthUrl() to generate the URL for the user to visit.gauth.Auth(code) to authorize and build the service.Your settings.yaml configuration will still be respected during this manual process.
from pydrive2.auth import GoogleAuth
gauth = GoogleAuth()
auth_url = gauth.GetAuthUrl() # Create authentication url user needs to visit
# ... user visits URL and provides code ...
code = "USER_PROVIDED_CODE"
gauth.Auth(code) # Authorize and build service from the code