Hey there, fellow developer! Ready to supercharge your Python projects with Google Drive integration? You're in the right place. We'll be using the google-api-python-client
package to make this happen. Buckle up, because we're about to take your app to the cloud!
Before we dive in, let's make sure you've got your ducks in a row:
Got all that? Great! Let's move on to the fun stuff.
First things first, let's get our hands on the google-api-python-client
package. It's as easy as pie:
pip install google-api-python-client
Now, let's tackle the authentication beast. We'll be using OAuth 2.0, because we're not savages.
from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import Flow # Set up the OAuth 2.0 flow flow = Flow.from_client_secrets_file( 'path/to/client_secret.json', scopes=['https://www.googleapis.com/auth/drive'] ) # Get the authorization URL auth_url, _ = flow.authorization_url(prompt='consent') # After the user grants permission, you'll get an authorization code # Use this code to fetch the credentials flow.fetch_token(code=authorization_code) credentials = flow.credentials
With our credentials in hand, let's initialize the Drive service:
from googleapiclient.discovery import build service = build('drive', 'v3', credentials=credentials)
Boom! You're connected. Feel the power!
Let's see what we've got in our Drive:
results = service.files().list(pageSize=10, fields="nextPageToken, files(id, name)").execute() items = results.get('files', []) if not items: print('No files found.') else: print('Files:') for item in items: print(u'{0} ({1})'.format(item['name'], item['id']))
Time to add some content to our Drive:
from googleapiclient.http import MediaFileUpload file_metadata = {'name': 'photo.jpg'} media = MediaFileUpload('photo.jpg', resumable=True) file = service.files().create(body=file_metadata, media_body=media, fields='id').execute() print('File ID: %s' % file.get('id'))
Let's grab that file back:
file_id = 'your_file_id' request = service.files().get_media(fileId=file_id) fh = io.BytesIO() downloader = MediaIoBaseDownload(fh, request) done = False while done is False: status, done = downloader.next_chunk() print("Download %d%%." % int(status.progress() * 100))
Time for a quick update:
file_id = 'your_file_id' file_metadata = {'name': 'updated_photo.jpg'} media = MediaFileUpload('updated_photo.jpg', resumable=True) updated_file = service.files().update(fileId=file_id, body=file_metadata, media_body=media).execute()
Out with the old:
file_id = 'your_file_id' service.files().delete(fileId=file_id).execute()
Let's find that needle in the haystack:
results = service.files().list(q="name contains 'photo'", fields="nextPageToken, files(id, name)").execute()
Sharing is caring:
def share_file(file_id, email): batch = service.new_batch_http_request(callback=callback) user_permission = { 'type': 'user', 'role': 'writer', 'emailAddress': email } batch.add(service.permissions().create( fileId=file_id, body=user_permission, fields='id', )) batch.execute()
Let's get organized:
folder_metadata = { 'name': 'My Projects', 'mimeType': 'application/vnd.google-apps.folder' } folder = service.files().create(body=folder_metadata, fields='id').execute() print('Folder ID: %s' % folder.get('id'))
Always expect the unexpected:
from googleapiclient.errors import HttpError try: # Your Google Drive API calls here except HttpError as error: print(f'An error occurred: {error}')
And remember, be nice to the API. Use exponential backoff for retries and stay within the quota limits.
Let's put it all together:
def backup_local_directory(local_dir, drive_folder_id): for root, dirs, files in os.walk(local_dir): for filename in files: filepath = os.path.join(root, filename) file_metadata = {'name': filename, 'parents': [drive_folder_id]} media = MediaFileUpload(filepath) file = service.files().create(body=file_metadata, media_body=media, fields='id').execute() print(f'File ID: {file.get("id")}') # Usage backup_local_directory('/path/to/local/directory', 'drive_folder_id')
And there you have it! You're now a Google Drive API ninja. Remember, with great power comes great responsibility. Use your newfound skills wisely, and happy coding!
For more advanced techniques and in-depth documentation, check out the official Google Drive API Python quickstart guide.
Now go forth and conquer the cloud!