Install & Compatibility
Where this runs
tested against v1.21.3 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.910 runs
installs and imports cleanly · install 0.0s · import 1.353s · 153.9MB
glibcpy 3.10–3.910 runs
installs and imports cleanly · install 5.8s · import 1.270s · 155MB
154MB installed
● package 154MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
GoogleAuth
✓ from pydrive2.auth import GoogleAuth
✗ from pydrive.auth import GoogleAuth
PyDrive2 is a fork; ensure you import from `pydrive2` not the original `pydrive`.
GoogleDrive
✓ from pydrive2.drive import GoogleDrive
✗ from pydrive.drive import GoogleDrive
PyDrive2 is a fork; ensure you import from `pydrive2` not the original `pydrive`.
This quickstart demonstrates how to authenticate with Google Drive using `PyDrive2` and then upload a simple text file. It utilizes `LocalWebserverAuth` for initial authorization and saves credentials for subsequent runs. Ensure you have downloaded your `client_secrets.json` from the Google API Console and placed it in your working directory. You must enable the Google Drive API for your project in the Google Cloud Console.
import os
from pydrive2.auth import GoogleAuth
from pydrive2.drive import GoogleDrive
# IMPORTANT: Place your 'client_secrets.json' file in the same directory
# as this script, or specify its path in gauth.settings['client_config_file'].
# Instructions to get client_secrets.json: https://docs.iterative.ai/PyDrive2/quickstart/#authentication
gauth = GoogleAuth()
# Uncomment the following line to specify a custom path for client_secrets.json
# gauth.settings['client_config_file'] = os.path.join(os.getcwd(), 'path_to_your', 'client_secrets.json')
# Try to load saved client credentials
try:
gauth.LoadCredentialsFile("mycreds.txt")
except Exception:
pass # File might not exist yet
if gauth.credentials is None:
# Authenticate if credentials are not found or invalid.
# For persistent access, ensure your OAuth client is configured for 'offline' access
# to receive a refresh token. This requires manual setup in Google Cloud Console.
gauth.LocalWebserverAuth()
elif gauth.access_token_expired:
# Refresh credentials if the access token has expired
gauth.Refresh()
else:
# Authorize with the loaded credentials
gauth.Authorize()
# Save the current credentials to a file for future use
gauth.SaveCredentialsFile("mycreds.txt")
drive = GoogleDrive(gauth)
# Create a text file and upload it to Google Drive
file_title = "MyTestFile_PyDrive2.txt"
file_content = "Hello, Google Drive from PyDrive2!"
file = drive.CreateFile({'title': file_title})
file.SetContentString(file_content)
file.Upload()
print(f"Uploaded file: {file['title']} (ID: {file['id']})")
# List files in the root folder of Google Drive
print("\nFiles in Google Drive (first 10):")
file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
for f in file_list:
print(f"Title: {f['title']}, ID: {f['id']}")
Debug
Known issues
breakingPython 3.7 support was dropped in PyDrive2 version 1.16.0. Users on Python 3.7 or older must upgrade their Python environment to 3.8 or newer.fixUpgrade your Python environment to 3.8 or a later version.
affects: >=1.16.0
gotchaThe original PyDrive library is deprecated and unmaintained. Using `pydrive` instead of `pydrive2` will lead to unpatched bugs and compatibility issues, especially with recent Google API changes.fixMigrate your code to use `pydrive2`. Update `pip install pydrive` to `pip install pydrive2` and change import statements from `pydrive` to `pydrive2`.
affects: <1.x (original PyDrive)
gotchaGoogle's deprecation of Out-of-Band (OOB) OAuth flows may affect older authentication methods. `LocalWebserverAuth` is the recommended interactive flow.fixEnsure your OAuth client is configured as a 'Web application' in the Google Cloud Console, and use `LocalWebserverAuth()` or service account authentication. For `LocalWebserverAuth`, ensure `http://localhost:8080/` is an authorized redirect URI.
affects: All versions, depending on Google's API changes.
gotchaVersions of `pyOpenSSL` and `cryptography` can cause import or runtime errors due to breaking changes in their APIs. Specific versions have been pinned in PyDrive2 to mitigate this.fixIf encountering issues, ensure you are on the latest `pydrive2` version, which includes dependency pinning. If problems persist, manually pin `pyOpenSSL` to `<=24.2.1` and `cryptography` to `<44` or as specified in `pydrive2`'s `pyproject.toml` or `setup.cfg` for your installed version.
affects: 1.21.2, 1.21.3 (and potentially older/newer versions depending on transitive dependencies)
gotchaFor persistent authentication that doesn't require re-authorization on every run, you need to ensure a refresh token is obtained. This typically requires setting `access_type='offline'` in your OAuth configuration and persisting credentials (e.g., using `gauth.SaveCredentialsFile()`). Without it, access tokens will expire, requiring re-authentication.fixWhen setting up your OAuth client in Google Cloud Console, ensure it's configured to grant offline access. In your code, if using `LocalWebserverAuth`, it typically handles this, but always save and load credentials. For service accounts, ensure the service account has appropriate permissions.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'pydrive'
The `pydrive2` library (or its predecessor `pydrive`) is not installed, or the Python environment where the script is run does not have access to the installed library. This can also occur if `pydrive` was installed but `pydrive2` is being imported, or vice versa.
fixInstall `pydrive2` using pip: `pip install pydrive2`. If using a virtual environment, ensure it is activated before installation. If you previously installed `pydrive`, consider uninstalling it (`pip uninstall pydrive`) to avoid conflicts.
FileNotFoundError: [Errno 2] No such file or directory: 'client_secrets.json'
The `client_secrets.json` file, which contains the OAuth 2.0 client credentials, is either missing from the expected directory, incorrectly named, or its path is not correctly specified for `GoogleAuth` to find it.
fixEnsure `client_secrets.json` is downloaded from the Google API Console (after creating an OAuth 2.0 Client ID for a 'Desktop app' or 'Web application'), renamed exactly to `client_secrets.json`, and placed in the same directory as your Python script, or specify its exact path to `gauth.LoadClientConfigFile('path/to/client_secrets.json')`. RefreshError: Access token refresh failed: invalid_grant: Token has been expired or revoked.
The refresh token used by `pydrive2` to obtain new access tokens has expired or been revoked. This often happens if the OAuth consent screen of your Google Cloud project is in 'Testing' status (limiting token validity to 7 days) or if the refresh token limit (100 per client ID) has been reached.
fixSet your Google Cloud project's OAuth consent screen publishing status to 'In production'. If the problem persists or for local development, delete the `credentials.json` file to force a fresh authentication flow. Ensure `gauth.auth_params = {'access_type': 'offline', 'prompt': 'consent'}` is set before calling `LocalWebserverAuth()` or `CommandLineAuth()` to guarantee a long-lived refresh token is issued. pydrive2.files.ApiRequestError: <HttpError 400 when requesting https://www.googleapis.com/upload/drive/v2/files?supportsTeamDrives...>
This HTTP 400 'Bad Request' error often occurs when attempting to upload large files (e.g., >100 MB) and simultaneously converting them to Google's native formats (like Google Docs or Sheets).
fixUpload the file without converting it to a Google native format. When creating the `GoogleDriveFile` object, ensure that the `mimeType` is set to the actual file's MIME type or omitted if you do not wish for Google Drive to convert it, allowing it to be stored as-is.
Pydrive error: No downloadLink/exportLinks for mimetype found in metadata
You are attempting to download a Google-native document (e.g., a Google Doc, Sheet, or Slide) directly without specifying an export `mimetype`. These files do not have a direct 'download link' in their native format and must be explicitly exported to another format.
fixWhen calling `GetContentFile()` or `GetContentString()` for Google-native files, provide an appropriate export `mimetype`. For example, to download a Google Doc as a PDF: `file.GetContentFile('document.pdf', mimetype='application/pdf')`, or a Google Sheet as an Excel file: `file.GetContentFile('spreadsheet.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')`. Upgrade
Version history
1.21.3latest on PyPI · released Nov 29, 2024
Audit
Dependencies
google-api-python-clientrequiredCore library for interacting with Google APIs.
oauth2clientrequiredHandles OAuth2.0 authentication for Google services.
PyYAMLrequiredUsed for configuration settings, especially for custom OAuth flows.
cryptographyrequiredA critical dependency for secure communication, often subject to version pinning for stability.
pyOpenSSLrequiredProvides SSL/TLS functionality, also frequently subject to version constraints.
fsspecoptionalEnables a filesystem-like interface for Google Drive, allowing standard file operations.