Search code examples
pythongoogle-drive-api

Google drive api Python - losing permission after upload to folder


Hopefully someone can help me here, as I'm struggling to see why this is happening. I have a file that I want to upload to a specific folder on Google drive. The code iterates through the returned list until it matches the folder name and retrieves the ID. Then uses this to upload to the folder. This works great first time and only first time. Once I have uploaded one file to that folder, on further attempts the returned list of files/folders excludes the folder in question. If I delete the folder contents (not the folder) and empty the trash it then works again. Many thanks in advance.

def get_files_and_creds(folder_name):
    try:
        creds = main()
        service = build("drive", "v3", credentials=creds)
        results = (
            service.files()
            .list(pageSize=10, fields="nextPageToken, files(id, name, mimeType, size, parents, modifiedTime)")
            .execute()
        )
        items = results.get("files", [])

        if not items:
            logging.error("No files found.")
            return
        for item in items:
            if item['name'] == folder_name:
                logging.debug("File list:"+str(item['name'])+":"+str(item['id']))
                folder_id = item['id']
            else:
                logging.info("No matching folder name:"+folder_name)
                return False
    except HttpError as e:
        logging.error("get_files:"+str(e))
        return False
    return folder_id, creds

def file_upload(upload_file, folder_name):
    try:
        logging.debug("folder name:"+str(folder_name)+" Filename:"+str(upload_file))
        data = get_files_and_creds(folder_name)
        folder_id = data[0]
        creds = data[1]
        logging.debug("FolderID:"+str(folder_id)+str(creds))
        service = build("drive", "v3", credentials=creds)
        file_metadata = {
            'name': os.path.basename(upload_file),
            'mimeType': '*/*',
            'parents': [folder_id]
            }
        media = MediaFileUpload(upload_file,
                                mimetype='*/*',
                                resumable=True)
        file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
        logging.debug('File ID: ' + file.get('id'))
    except Exception as e:
        logging.error("file_upload"+str(e))

Solution

  • There is an issue in your function get_files_and_creds, if the first item is not the target folder it return False in the first iteration.

    To avoid that return folder_id and creds if the folder found. Here is updated code :

    def get_files_and_creds(folder_name):
        try:
            creds = main()
            service = build("drive", "v3", credentials=creds)
            results = (
                service.files()
                .list(pageSize=10, fields="nextPageToken, files(id, name, mimeType, size, parents, modifiedTime)")
                .execute()
            )
            items = results.get("files", [])
    
            if not items:
                logging.error("No files found.")
                return
            for item in items:
                if item['name'] == folder_name:
                    logging.debug("File list:"+str(item['name'])+":"+str(item['id']))
                    folder_id = item['id']
                    return folder_id, creds
    
            logging.info("No matching folder name:"+folder_name)
            return False
            
        except HttpError as e:
            logging.error("get_files:"+str(e))
            return False