Return union of doc and dct, after making sure that dct has been added to doc in `collection`. This function does not modify either `doc` or `dct`.
(self, doc, dct, collection=None, do_sanity_checks=True)
| 525 | self.update(doc, dict(refresh_time=coarse_utcnow())) |
| 526 | |
| 527 | def update(self, doc, dct, collection=None, do_sanity_checks=True): |
| 528 | """Return union of doc and dct, after making sure that dct has been |
| 529 | added to doc in `collection`. |
| 530 | |
| 531 | This function does not modify either `doc` or `dct`. |
| 532 | |
| 533 | """ |
| 534 | if collection is None: |
| 535 | collection = self.collection |
| 536 | |
| 537 | dct = copy.deepcopy(dct) |
| 538 | if "_id" not in doc: |
| 539 | raise ValueError('doc must have an "_id" key to be updated') |
| 540 | |
| 541 | if "_id" in dct: |
| 542 | if dct["_id"] != doc["_id"]: |
| 543 | raise ValueError("cannot update the _id field") |
| 544 | del dct["_id"] |
| 545 | |
| 546 | if "version" in dct: |
| 547 | if dct["version"] != doc["version"]: |
| 548 | warnings.warn('Ignoring "version" field in update dictionary') |
| 549 | |
| 550 | if "version" in doc: |
| 551 | doc_query = dict(_id=doc["_id"], version=doc["version"]) |
| 552 | dct["version"] = doc["version"] + 1 |
| 553 | else: |
| 554 | doc_query = dict(_id=doc["_id"]) |
| 555 | dct["version"] = 1 |
| 556 | try: |
| 557 | # warning - if doc matches nothing then this function succeeds |
| 558 | # N.B. this matches *at most* one entry, and possibly zero |
| 559 | collection.update(doc_query, {"$set": dct}, upsert=False, multi=False) |
| 560 | except pymongo.errors.OperationFailure as e: |
| 561 | # -- translate pymongo error class into hyperopt error class |
| 562 | # see insert() code for rationale. |
| 563 | raise OperationFailure(e) |
| 564 | |
| 565 | # update doc in-place to match what happened on the server side |
| 566 | doc.update(dct) |
| 567 | |
| 568 | if do_sanity_checks: |
| 569 | server_doc = collection.find_one( |
| 570 | dict(_id=doc["_id"], version=doc["version"]) |
| 571 | ) |
| 572 | if server_doc is None: |
| 573 | raise OperationFailure("updated doc not found : %s" % str(doc)) |
| 574 | return doc |
| 575 | |
| 576 | def attachment_names(self, doc): |
| 577 | def as_str(name_id): |