首页 > 解决方案 > Python——在循环中丢失并且无法获得正确的值

问题描述

我已经搜索了两天并为 4 编写 Python 代码。我需要找到一个可能嵌套在另一个文件夹中的文件夹,然后返回该文件夹 ID 和另一个属性。如果文件夹存在于顶层,我会得到正确的响应,如果它存在于该层之下,我什么也得不到。我想我要问的是,我到底能做些什么来停止函数和所有父函数?一旦我找到了价值,我只想让这一切停止。如果它更快,我不反对以不同的方式(比如创建文件夹属性列表)。

def find_folder(header, folder_list, name):
    x = len(name)
    for folder in folder_list:
        if folder['wstype'] == 'folder':
            if folder['has_subfolders'] == True:
                response = requests.get('https://' + server + '/work/api/v2/customers/1/libraries/active/folders/'
                                        + folder['id'] + '/children', headers=header)
                find_folder(header, response.json()['data'], name)
            if folder['name'][:x] == name:
                #found it, now we need the class on the folder
                resp = requests.get(base_url + '/folders/' + folder['id'] + '/name-value-pairs', headers=header)
                nvps = resp.json()['data']
                docclass = nvps.get('iMan___8','')
                fID = folder['id']
                return fID, docclass

fID, docclass = find_folder(headers, wksp, foldername[1])

输出看起来像这样。我要查找的文件夹是 Tax Filings 和 Working Documents 是空间中的最后一个文件夹。代码在到达 Tax Filings 时应该停止并传回 fID 和 docclass

Tax Documents (P98722)
  Elections and Other Documents (P98722)
  Tax Filings and Estimated Income (P98722)
Working Documents (P98722)
Traceback (most recent call last):   File "C:/Users/mmasteju/AppData/Local/Programs/Python/Python37/foobar.py", line 163, in <module> main()
File "C:/Users/mmasteju/AppData/Local/Programs/Python/Python37/foobar.py",line 145, in main
fID, docclass = find_folder(headers, wksp, foldername[1])
TypeError: cannot unpack non-iterable NoneType object

我试过break and pass,我试过全局变量,但效果很差,我不知道下一步该怎么做。

提前致谢

标签: python

解决方案


def find_folder(header, folder_list, name):
    x = len(name)
    
    for folder in folder_list:
        if folder['wstype'] == 'folder' and folder['folder_type'] == 'regular':
            print(folder['name'], folder['folder_type'])
            if folder['has_subfolders'] == True:
                response = requests.get('https://' + server + '/work/api/v2/customers/1/libraries/active/folders/'
                                        + folder['id'] + '/children', headers=header)
                ffid = find_folder(header, response.json()['data'], name)
                if ffid is not None:
                    return ffid
            if folder['name'][:x] == name:
                fID = folder['id']
                if fID is not None:
                    return fID

def getclass(header, folder_id):
    resp = requests.get(base_url + '/folders/' + folder_id + '/name-value-pairs', headers=header)
    nvps = resp.json()['data']
    docclass = nvps.get('iMan___8','')
    return docclass

fID = find_folder(headers, wksp, foldername[1])
if fID is not None:
    docclass = getclass(headers, fID)

谢谢@PaulMcG——你让我走上了正确的道路。-1,000,000 @roganjosh -1,000,000 @tripleee——你们没用


推荐阅读