Pydrive Reading but not Writting

48 views Asked by At

I'm running the following code to try to upload files in a Shared Google Drive. I have a credentials.json file that I use to authenticate in Google Drive, and when I run the following code, it works perfectly fine:

def authenticate_drive(drive_json_path: str):
    """Authenticate and return the GoogleDrive object.
    
    Args:
    drive_json_path (str): Contains the path to the Google Drive .json credentials file
    
    Returns:
    drive (GoogleAuth): Returns a GoogleAuth session that allows making API calls
    """
    gauth = GoogleAuth()
    gauth.credentials = sca.from_json_keyfile_name(drive_json_path, ['https://www.googleapis.com/auth/drive'])
    drive = GoogleDrive(gauth)
    return drive

def list_files_in_folder(drive, folder_id):
    # List all files in the specified folder
    file_list =  drive.ListFile({'q':f"'{folder_id}' in parents and trashed=false", \
                                 'corpora': 'teamDrive', 'teamDriveId': team_drive_id,
                                 'includeTeamDriveItems': True, 'supportsTeamDrives': True}).GetList()

    if file_list:
        print(f'Files in folder {folder_id}:')
        for file1 in file_list:
            print(f'- {file1["title"]} (ID: {file1["id"]})')
    else:
        print(f'No files found in the specified folder.')

drive = authenticate_drive(credentials_path)
list_files_in_folder(drive, folder_id)

The mail in the .json credentials file has been added to manager status, IDs (both folder and teamDrive) are correct, and it returns the three files in this directory.

When I try to run this other code though:

def authenticate_drive(drive_json_path: str):
    """Authenticate and return the GoogleDrive object.
    
    Args:
    drive_json_path (str): Contains the path to the Google Drive .json credentials file
    
    Returns:
    drive (GoogleAuth): Returns a GoogleAuth session that allows making API calls
    """
    gauth = GoogleAuth()
    gauth.credentials = sca.from_json_keyfile_name(drive_json_path, ['https://www.googleapis.com/auth/drive'])
    drive = GoogleDrive(gauth)
    return drive

def create_text_file(drive, folder_id, content):
    # Create a text file with the specified content
    file_metadata = {
        'title': 'hello.txt',
        'id' : folder_id,
        'parents': [{
            'kind': 'drive#fileLink',
            'teamDriveId': team_drive_id
        }],
        'supportsTeamDrives': True,
        'includeTeamDriveItems': True
    }
            
    file_content = drive.CreateFile(file_metadata)
    file_content.SetContentString(content)
    file_content.Upload()

    print(f'Text file created with ID: {file_content.get("id")}')

drive = authenticate_drive(credentials_path)
create_text_file(drive, folder_id, content)

I get the following error:

ApiRequestError: <HttpError 404 when requesting https://www.googleapis.com/drive/v2/files/moooo090909?alt=json returned "File not found: moooo090909". Details: "[{'message': 'File not found: moooo090909', 'domain': 'global', 'reason': 'notFound', 'location': 'file', 'locationType': 'other'}]">

(this second part is what

{
  "error": {
    "code": 403,
    "message": "The request is missing a valid API key.",
    "errors": [
      {
        "message": "The request is missing a valid API key.",
        "domain": "global",
        "reason": "forbidden"
      }
    ],
    "status": "PERMISSION_DENIED"
  }
}

If somebody could help me it would be grand.

1

There are 1 answers

0
Tanaike On

In your showing script, how about the following modification? In this case, create_text_file is modified.

Modified script:

def create_text_file(drive, folder_id, content):
    # Create a text file with the specified content
    file_metadata = {
        "title": "hello.txt",
        "parents": [{"id": folder_id}],
    }
    file_content = drive.CreateFile(file_metadata)
    file_content.SetContentString(content)
    file_content.Upload(param={"supportsAllDrives": True})
    print(f'Text file created with ID: {file_content.get("id")}')
  • Under folder_id and content are valid values, when I tested this modified script, I confirmed that the script worked and a text file was created to the specific folder in the shared drive.

  • The folder ID is the unique value. So, when you have already known the folder ID, you can directly use the folder ID as the parent folder ID.

Note:

  • In this case, it supposes that your client has permission to write to your shared drive. Please be careful about this.

References: