Google Drive API - Copy folder

There is no usual way to copy a folder in Google Drive using the API. But, We can still create folders and have the copy file api. So, following these steps we can copy folders:


1. Insert a new folder
2. Make a copy of all files inside the source folder
3. Assign the new folder as the parent of the copied files
4. For sub folders, use recursion to copy.



I've implemented that flow:


from apiclient import errors

def copy_file(service, origin_file_id, copy_title, parentid=None):
    """Copy an existing file.

    Args:
        service: Drive API service instance.
        origin_file_id: ID of the origin file to copy.
        copy_title: Title of the copy.

    Returns:
        The copied file if successful, None otherwise.
    """
    copied_file = {'title': copy_title}
    if parentid:
        copied_file['parents'] = [{'id': parentid}]
    try:
        file = service.files().copy(
                    fileId=origin_file_id, body=copied_file).execute()
        return file['id']
    except errors.HttpError, error:
        print 'An error occurred: %s' % error

    return None


def insert_folder(service, title, desc, parentid=None):
    body = {
        'title': title,
        'description': desc,
        'mimeType': 'application/vnd.google-apps.folder'
    }
    if parentid:
        body['parents'] = [{'id': parentid}]

    try:
        folder = service.files().insert(body=body).execute()
        # pprint.pprint(folder)
        return folder['id']
    except errors.HttpError, error:
        print 'An error occurred: %s' % error
    return None


def copy_folder(service, folder_id, folder_title, parentid=None):
    new_created_ids = []
    new_folderid = insert_folder(service, folder_title, folder_title, parentid)
    new_created_ids.append({'src_id': folder_id, 'dest_id': new_folderid})

    query_string = "'%s' in parents" % (folder_id)

    files = search_files(service, query_string)
    for file in files:
        if file['mimeType'] == 'application/vnd.google-apps.folder':

            ### Use recursion to copy sub-folder
            sub_created_ids = copy_folder(service, file['id'], file['title'], parentid=new_folderid)

            new_created_ids += sub_created_ids
        else:
            copied_fileid = copy_file(service, file['id'], file['title'], parentid=new_folderid)
            new_created_ids.append({'src_id': file['id'], 'dest_id': copied_fileid})

    return new_created_ids



For more utilities, take a look at GDM (Google Drive Migration) project: https://github.com/dangtrinh/gdm

Comments