Search code examples
pythonbatch-processinggoogle-api-python-client

Google Drive API Python Client: How to retrieve list of created folder IDs when created in batch?


Following code works to create a set of folders using batch request.

from google.oauth2 import service_account
from googleapiclient import discovery, http

credentials = service_account.Credentials.from_service_account_file('/home/user/Documents/code/credentials.json')
scoped_credentials = credentials.with_scopes(['https://www.googleapis.com/auth/drive'])
drive = discovery.build('drive', 'v3', credentials=scoped_credentials)

names = ['test1', 'test2', 'test3']
batch = drive.new_batch_http_request()

for name in names:
    folder_metadata = {'name': name,
                       'mimeType': 'application/vnd.google-apps.folder'}
    batch.add(drive.files().create(body=folder_metadata, fields='id'))
res = batch.execute()

However, I would like to retrieve the list of tuples (folder_name_, folder_id). res object returned is None.

Any ideas?

Edit

Here is an updated code, but res remains None.

names = ['test1', 'test2', 'test3']

def receive_callback(request_id, response, exception):
    #response should have the details about folders
    return response['id'], response['name']

# batch = drive.new_batch_http_request()
batch = drive.new_batch_http_request(receive_callback)

for name in names:
    folder_metadata = {'name': name,
                       'mimeType': 'application/vnd.google-apps.folder'}
    batch.add(drive.files().create(body=folder_metadata, fields='id, name'))
res = batch.execute()

Thanks for any help. Bests,


Solution

  • def receive_callback(request_id, response, exception):
        #response should have the details about folders
    

    replace

    batch = drive.new_batch_http_request()
    

    with

    batch = drive.new_batch_http_request(receive_callback)
    

    You will receive the response of each request of the folder creation request that you made