gpt4 book ai didi

python - 关于mongodb更新操作参数safe=True的问题

转载 作者:可可西里 更新时间:2023-11-01 09:11:51 26 4
gpt4 key购买 nike

我正在使用 pymongo python 模块处理 mongodb 数据库。我的代码中有一个函数,调用时会按如下方式更新集合中的记录。

for record in coll.find(<some query here>):
#Code here
#...
#...
coll.update({ '_id' : record['_id'] },record)

现在,如果我修改代码如下:

for record in coll.find(<some query here>):
try:
#Code here
#...
#...
coll.update({ '_id' : record['_id'] },record,safe=True)
except:
#Handle exception here

这是否意味着更新失败时会抛出异常,或者不会抛出异常,更新只会跳过导致问题的记录?

请帮忙谢谢

最佳答案

tryexcept 永远不会引发异常。它们只是处理抛出的异常。

如果 update 在失败时抛出异常,except 将处理该异常,然后循环将继续(除非您在中使用 raise except 子句)。

如果 update 没有在失败时抛出异常,而是返回 None(或类似的东西),而您想要它要抛出异常,您可以使用:

if coll.update(...) is None: # or whatever it returns on failure
raise ValueError # or your custom Exception subclass

请注意,您应该始终指定要捕获的异常,并且只用 try 将要捕获的代码行包围起来,这样您就不会在代码中隐藏其他错误:

for record in coll.find(<some query here>):
#Code here
#...
#...
try:
coll.update({ '_id' : record['_id'] },record,safe=True)
except SpecificException:
#Handle exception here
except OtherSpecificException:
#Handle exception here
else:
#extra stuff to do if there was no exception

参见 try Statement , Built-in Exceptions , 和 Errors and Exceptions .

关于python - 关于mongodb更新操作参数safe=True的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7092407/

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