我有一个简单的for循环,它循环访问本地数据库中的所有对象。对于每个对象,我引用一个presalesEngineer并将该ID传递给API调用以检索JSON响应。但是,数据库中有没有presalesEngineer值的记录。在这种情况下,当错误的HttpError传递给URL调用时,空字符串将引发APIpresalesEngineer不存在时如何处理,这样API不会传递空值?

views.py

objects = Opportunity.objects.all()

    for object in objects:
        try:
            ps_e = object.presalesEngineer
            if ps_e:
                presales_engineers = [cwObj.get_member_by_id(ps_e) for object in objects]
            else:
                presales_engineers = 'None'
        except NameError:
            presales_engineers = 'None'

最佳答案

此代码块应尝试获取您对象的presalesEngineer或返回None(请注意,字符串“ None”不等于pytohon对象None)

for object in objects:
    try:
        ps_e = object.presalesEngineer
        # Do stuff with an object you know for sure will not trigger an exception
        # Something like:
        # if ps_e != '': < the object is not an empty string
        # or
        # if ps_e: < the object is not None
        # after you pass whatever checks you deem necessary, you launch your API call.
    except AttributeError:
        # You can either pass here or return a None object/Empty list
        ps_e = None


可能的实现如下:

# Empty list of whatever you are searching for
engineers = []
for my_object in objects:
    try:
        ps_e = my_object.presalesEngineer
        # This is here to avoid none values in your API call
        if ps_e:
            # Just in case your API call falls
            # It will fail silently in this try codeblock
            try:
                # Assuming cwObj is your driver/API endpoint builder
                # And that you only get one single string as response
                # And that string is not some data structure that you need to split
                my_desired_id = cwObj.get_member_by_id(ps_e)
                engineers.append(my_desired_id)
            # Using bare except statements is not a good idea
            # Use HttpError here if you don't want to pass on any exception
            except:
                pass
    except AttributeError:
        # You can either pass here or return a None object/Empty list
        pass
print engineers

关于python - 物品不存在时如何处理,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57147513/

10-12 22:49