gpt4 book ai didi

python - 项目不存在时如何处理

转载 作者:行者123 更新时间:2023-12-01 07:32:35 25 4
gpt4 key购买 nike

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

View .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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com