PyDrive
PyDrive is a Python wrapper library for the Google Drive API that simplifies common tasks like authentication, file upload, download, and management. The current version is 1.3.1. However, the original PyDrive project is deprecated and no longer maintained. Its last release was in 2016, and the GitHub repository was archived in July 2021. Users are strongly encouraged to consider `PyDrive2` (pypi.org/project/PyDrive2), an actively maintained fork, for ongoing development and support.
Warnings
- breaking The original PyDrive project is explicitly deprecated and no longer maintained. Its GitHub repository has been archived. No further changes or bug fixes will be made, leading to potential future incompatibilities and security vulnerabilities.
- deprecated PyDrive relies heavily on the `oauth2client` library for authentication, which is deprecated by Google and largely unmaintained. This can lead to security vulnerabilities, lack of thread-safety, and incompatibilities with newer Python versions or related libraries (e.g., `PyOpenSSL` or `httplib2`).
- gotcha Authentication refresh tokens obtained from Google Cloud projects with an 'external user type' and a 'Testing' publishing status will expire after 7 days, requiring manual re-authentication.
- gotcha By default, PyDrive's authentication might only grant access to root-level files and folders on your Google Drive. Accessing subfolders or files outside the default scope requires explicit configuration.
- gotcha The `client_secrets.json` file, required for authentication, must be named exactly `client_secrets.json` and placed in the working directory of your script for PyDrive to find it automatically. Incorrect naming or placement will result in authentication errors.
Install
-
pip install pydrive
Imports
- GoogleAuth
from pydrive.auth import GoogleAuth
- GoogleDrive
from pydrive.drive import GoogleDrive
Quickstart
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import os
# --- Pre-requisites for Quickstart ---
# 1. Go to Google API Console (console.developers.google.com/apis/credentials)
# 2. Create a new project or select an existing one.
# 3. Enable the 'Google Drive API'.
# 4. Create 'OAuth client ID' credentials:
# - Application type: 'Web application'
# - Authorized JavaScript origins: http://localhost:8080
# - Authorized redirect URIs: http://localhost:8080/
# 5. Download the client configuration JSON file and rename it to 'client_secrets.json'.
# 6. Place 'client_secrets.json' in the same directory as this script.
# -------------------------------------
gauth = GoogleAuth()
# Try to load saved client credentials (e.g., from 'credentials.json' generated previously)
gauth.LoadCredentials()
if gauth.credentials is None:
# Authenticate if credentials are not found
print("Performing initial authentication via local webserver...")
gauth.LocalWebserverAuth() # Creates local webserver and auto handles authentication.
elif gauth.access_token_expired:
# Refresh them if expired
print("Refreshing expired access token...")
gauth.Refresh()
else:
# Initialize the saved credentials
print("Using existing credentials.")
gauth.Authorize()
# Save the current credentials to a file for future use
gauth.SaveCredentials()
drive = GoogleDrive(gauth)
# --- Create and Upload a File ---
file_title = "PyDrive_Registry_Test_File.txt"
file_content = "This is a test file uploaded using PyDrive from the registry quickstart. Hello, Google Drive!"
# Create GoogleDriveFile instance with metadata.
file_metadata = {'title': file_title, 'mimeType': 'text/plain'}
file1 = drive.CreateFile(file_metadata)
file1.SetContentString(file_content) # Set content from a string
file1.Upload() # Upload the file to Google Drive
print(f"\nSuccessfully uploaded file: '{file1['title']}' (ID: {file1['id']})")
# --- List Files (optional, for demonstration) ---
print(f"\nSearching for file with title '{file_title}'...")
file_list = drive.ListFile({'q': f"'me' in owners and title = '{file_title}' and trashed = false"}).GetList()
if file_list:
print(f"Found {len(file_list)} file(s) with title '{file_title}':")
for file in file_list:
print(f" - Title: {file['title']}, ID: {file['id']}, MimeType: {file['mimeType']}")
else:
print(f"No file found with title '{file_title}'.")