What's the best Python method for uploading files to Google Drive?

Hey everyone! I’m trying to figure out how to use Python to upload different types of files to Google Drive. It’s for a backup system I’m setting up on my Linux server.

I’m not just talking about files that can be turned into Google Docs. I need to handle all sorts of file types. Does anyone know a simple and clean way to do this?

I’ve seen some solutions for working with Google Docs, but I’m not sure if they’ll work for my situation. Any tips or code examples would be super helpful!

Here’s a basic idea of what I’m thinking:

def upload_to_gdrive(file_path):
    # Connect to Google Drive
    drive_service = create_drive_service()
    
    # Get file info
    file_name = os.path.basename(file_path)
    file_type = mimetypes.guess_type(file_path)[0]
    
    # Create file metadata
    file_metadata = {'name': file_name}
    
    # Upload file
    media = MediaFileUpload(file_path, mimetype=file_type)
    file = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute()
    
    print(f'File ID: {file.get('id')}')

# Usage
upload_to_gdrive('/path/to/your/file.ext')

This is just a starting point. I’d love to hear if there are better ways to do this or if I’m missing something important. Thanks in advance for any help!

I’ve had success using the Google Drive API with the google-auth and google-auth-oauthlib libraries for authentication, and googleapiclient for interacting with Drive. Your approach looks solid, but I’d suggest a few tweaks:

  1. Use chunked upload for large files to avoid timeouts.
  2. Implement retry logic for network issues.
  3. Add error handling for common scenarios.

Here’s a snippet that incorporates these improvements:

from googleapiclient.http import MediaFileUpload
from googleapiclient.errors import HttpError
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

def upload_to_gdrive(file_path):
    creds = get_credentials()
    service = build('drive', 'v3', credentials=creds)
    
    file_metadata = {'name': os.path.basename(file_path)}
    media = MediaFileUpload(file_path, resumable=True)
    
    try:
        file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
        print(f'File ID: {file.get('id')}')
    except HttpError as error:
        print(f'An error occurred: {error}')
        file = None
    
    return file

# Implement get_credentials() to handle OAuth2 flow

This should give you a more robust solution for your backup system.

I’ve been using the PyDrive library for uploading files to Google Drive, and it’s been a game-changer. It simplifies the authentication process and provides a clean interface for file operations.

Here’s a quick example of how you could use it:

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)

def upload_to_gdrive(file_path):
    file = drive.CreateFile({'title': os.path.basename(file_path)})
    file.SetContentFile(file_path)
    file.Upload()
    print(f'File ID: {file["id"]}')

upload_to_gdrive('/path/to/your/file.ext')

This approach handles different file types automatically and even supports folder creation and file searching. It’s been reliable for my backup needs, and the documentation is pretty solid if you need to dive deeper into more advanced features.