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

发布于 2024-11-30 07:10:08 字数 551 浏览 2 评论 0 原文

我使用 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

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

请帮忙 谢谢

Im working a mongodb database using pymongo python module. I have a function in my code which when called updates the records in the collection as follows.

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

Now, if i modify the code as follows :

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

Does this mean an exception will be thrown when update fails or no exception will be thrown and update will just skip the record causing a problem ?

Please Help
Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

纸伞微斜 2024-12-07 07:10:08

try except 永远不会引发异常。他们只是处理抛出的异常。

如果 update 在失败时抛出异常, except 将处理该异常,然后循环将继续(除非您在 raise 中使用 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 语句内置异常错误和异常

try and except never cause an exception to be thrown. They simply handle thrown exceptions.

If update throws an exception on failure, the except will handle the exception, then the loop will continue (unless you use raise in the except clause).

If update doesn't throw an exception on failure, but instead returns None (or something like that), and you want it to throw an exception, you can use:

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

Note you should always specify which exception you want to catch, and only surround the lines of code where you want to catch it with try, so you don't hide other errors in your code:

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

See the try Statement, Built-in Exceptions, and Errors and Exceptions.

ㄖ落Θ余辉 2024-12-07 07:10:08

使用 safe=True 将导致抛出异常(类型为 pymongo.errors.OperationFailure 或子类)(请参阅 pymongo 文档 了解更多信息)如果数据库响应错误。例如,这里我在唯一索引上导致重复键违规:(

>>> db.bar.insert({'a': 1, 'b': 1})
ObjectId('4e4bc586c67f060b25000000')
>>> db.bar.ensure_index('a', unique=True)
u'a_1'
>>> db.bar.insert({'a': 2, 'b': 1}, safe=True)
ObjectId('4e4bc71fc67f060b25000003')
>>> db.bar.update({'a': 2}, {'a': 1}, safe=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/pymongo/collection.py", line 368, in update
    spec, document, safe, kwargs), safe)
  File "/Library/Python/2.7/site-packages/pymongo/connection.py", line 770, in _send_message
    return self.__check_response_to_last_error(response)
  File "/Library/Python/2.7/site-packages/pymongo/connection.py", line 718, in __check_response_to_last_error
    raise DuplicateKeyError(error["err"])
pymongo.errors.DuplicateKeyError: E11000 duplicate key error index: test.bar.$a_1  dup key: { : 1 }

请注意,DuplicateKeyErrorOperationFailure 的子类,因此除了OperationFailure:...< /code> 将按预期工作)。

除了 update() 之外,save()insert()remove() 都接受safe 关键字参数。您还可以在Connection 级别设置safe,这样您就不必将其包含在每个修改数据库的调用中。

Using safe=True will cause exceptions (of type pymongo.errors.OperationFailure or subclasses) to be thrown (see the pymongo docs for more information) if the database responds with an error. For example, here I cause a duplicate key violation on a unique index:

>>> db.bar.insert({'a': 1, 'b': 1})
ObjectId('4e4bc586c67f060b25000000')
>>> db.bar.ensure_index('a', unique=True)
u'a_1'
>>> db.bar.insert({'a': 2, 'b': 1}, safe=True)
ObjectId('4e4bc71fc67f060b25000003')
>>> db.bar.update({'a': 2}, {'a': 1}, safe=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/pymongo/collection.py", line 368, in update
    spec, document, safe, kwargs), safe)
  File "/Library/Python/2.7/site-packages/pymongo/connection.py", line 770, in _send_message
    return self.__check_response_to_last_error(response)
  File "/Library/Python/2.7/site-packages/pymongo/connection.py", line 718, in __check_response_to_last_error
    raise DuplicateKeyError(error["err"])
pymongo.errors.DuplicateKeyError: E11000 duplicate key error index: test.bar.$a_1  dup key: { : 1 }

(Note that DuplicateKeyError is a subclass of OperationFailure, so except OperationFailure: ... would work as expected).

In addition to update(), save(), insert(), and remove() all accept the safe keyword argument. You can also set safe at the Connection level, so that you don't have to include it in each call that modifies the database.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文