Question about safe=True parameter for update operation of mongodb
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 mod开发者_运维技巧ify 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
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.
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.
精彩评论