upload files to google drive

How to upload files to google drive in Django?

0 / 0 2 Mins Admin

January 4, 2023

10 Comments

The Google API Client Library for Python is designed for developers of Python client applications. It provides easy and flexible access to several Google APIs. To upload files to Google Drive in Django, you can use the Google Drive API.

  1. First, you will need to set up a project in the Google Cloud Console and enable the Drive API.
  2. Next, you will need to install the Google API Python Client library in your Django project. You can do this by running the following command:
pip install google-api-python-client
  1. Once you have installed the library, you will need to authenticate your Django app with the Google Drive API. You can do this by creating a service account and downloading the private key file. Then, you can use the google.oauth2.credentials.Credentials class to authenticate your app and authorize it to access the Drive API.
  2. To upload a file to Google Drive, you can use the drive_service.files().create() method. This method takes a GoogleDriveFile object as an argument, which you can populate with the metadata for the file you want to upload, such as the name and MIME type. You can then use the media parameter to set the content of the file and the execute() method to upload it to Google Drive.

Here is some sample code that demonstrates how to upload a file to Google Drive using the Google Drive API in Django:

from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

def upload_file(file_path, file_name):
    try:
        # Load the service account key file
        credentials = Credentials.from_service_account_file(
            '/path/to/service-account-credentials.json', scopes=['https://www.googleapis.com/auth/drive'])

        # Create a service object
        service = build('drive', 'v3', credentials=credentials)

        # Read the file content
        with open(file_path, 'rb') as file:
            file_content = file.read()

        # Create a Google Drive file object
        file_metadata = {'name': file_name}
        media = MediaFileUpload(file_path,
                                mimetype='text/plain',
                                resumable=True)

        # Upload the file to Google Drive
        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

upload_file('/path/to/file.txt', 'My File')