如何修复Box SDK get_items()仅获取15个文件夹的分页问题?
修复Box SDK分页获取文件夹的问题
你的代码主要有三个问题导致分页失效:
- 参数名不匹配:
get_box_folder_id函数第一个参数定义为items,但调用时传入的是box_client,导致函数内部使用的box_client实际是错误的变量,引发逻辑混乱。 - 迭代器耗尽问题:Box SDK的
get_items()返回的是BoxCollection迭代器,你先遍历了一次items,之后再用len(list(items))会得到0,因为迭代器已经被耗尽,无法正确判断是否还有更多数据。 - 递归逻辑依赖错误的长度判断:因为迭代器耗尽,
len(list(items)) < limit总是成立,导致直接返回None,不会进入下一页递归。
修复后的代码
def lambda_handler(event, context): box_client = get_box_jwt_client() target_folder_name = "my_test_folder" box_folder_id = get_box_folder_id(box_client, target_folder_name) if box_folder_id: print(f"Found folder ID: {box_folder_id}") else: print(f"Folder '{target_folder_name}' not found") def get_box_folder_id(box_client, target_folder_name, root_folder_id="0", limit=200, offset=0): """ Recursively fetches items from a Box folder in batches and returns the folder ID of the target folder. """ # 获取当前页的items并转为列表保存,避免迭代器耗尽 items_response = box_client.folder(root_folder_id).get_items(limit=limit, offset=offset) items = list(items_response) for item in items: if item.name == target_folder_name and item.type == 'folder': print(f"Folder '{target_folder_name}' found with ID: {item.id}") return item.id # 找到目标文件夹后立即返回ID # 判断当前页数量是否小于limit,小于则说明没有更多页 if len(items) < limit: return None # 递归获取下一页,offset累加当前limit return get_box_folder_id(box_client, target_folder_name, root_folder_id, limit, offset + limit)
关键修复点说明
- 修正参数名:把
get_box_folder_id的第一个参数改为box_client,和调用时传入的变量一致,确保函数内部能正确使用Box客户端。 - 预存items列表:先把
get_items()返回的迭代器转为列表items,这样遍历后依然可以获取列表长度,用于判断是否还有下一页。 - 基于列表长度判断分页:用
len(items)和limit对比,准确判断是否还有更多数据需要获取,保证递归能正常触发。
内容的提问来源于stack exchange,提问作者Rick
相关产品推荐
相关产品推荐

