Corresponds to PATCH request with a resource identifier, modifying a single document in the database
482553
async def modify(self, **kwargs):
        '''
        
        '''
        try:
            pk = self.pk_type(kwargs['pk'])
            # modify is a class method on MongoCollectionMixin
            result = await self._meta.object_class.modify(self.db, key=pk, data=self.data)
            if result is None:
                raise NotFound('Object matching the given {} was not found'.format(self.pk))
            return await result.serialize()
        except Exception as ex:
            logger.exception(ex)
            raise BadRequest(ex)
461165
function update(req, res, next) {
    for (var key in req.body) {
      req.body[key] = utils.toNative(req.body[key])
    }
    var resource = db(req.params.resource)
      .update(utils.toNative(req._internal.filters.id), req.body)
    if (resource) {
      res.jsonp(resource)
    } else {
      res.status(404).jsonp({})
    }
  }
467564
def update(callback=None, path=None, method=Method.PUT, resource=None, tags=None, summary="Update specified resource.",
           middleware=None):
    # type: (Callable, Path, Methods, Resource, Tags, str, List[Any]) -> Operation
    
    def inner(c):
        op = ResourceOperation(c, path or PathParam('{key_field}'), method, resource, tags, summary, middleware)
        op.responses.add(Response(HTTPStatus.NO_CONTENT, "{name} has been updated."))
        op.responses.add(Response(HTTPStatus.BAD_REQUEST, "Validation failed.", Error))
        op.responses.add(Response(HTTPStatus.NOT_FOUND, "Not found", Error))
        return op
    return inner(callback) if callback else inner
1197766
def edit_resource(self, request):
        
        self.location_query = request.uri_query
        self.payload = (request.content_type, request.payload)
888096
def patch(self, *args, **kwargs):
        """"""
        json_data = request.get_json() or {}

        relationship_field, model_relationship_field, related_type_, related_id_field = self._get_relationship_data()

        if 'data' not in json_data:
            raise BadRequest('You must provide data with a "data" route node', source={'pointer': '/data'})
        if isinstance(json_data['data'], dict):
            if 'type' not in json_data['data']:
                raise BadRequest('Missing type in "data" node', source={'pointer': '/data/type'})
            if 'id' not in json_data['data']:
                raise BadRequest('Missing id in "data" node', source={'pointer': '/data/id'})
            if json_data['data']['type'] != related_type_:
                raise InvalidType('The type field does not match the resource type', source={'pointer': '/data/type'})
        if isinstance(json_data['data'], list):
            for obj in json_data['data']:
                if 'type' not in obj:
                    raise BadRequest('Missing type in "data" node', source={'pointer': '/data/type'})
                if 'id' not in obj:
                    raise BadRequest('Missing id in "data" node', source={'pointer': '/data/id'})
                if obj['type'] != related_type_:
                    raise InvalidType('The type provided does not match the resource type',
                                      source={'pointer': '/data/type'})

        self.before_patch(args, kwargs, json_data=json_data)

        obj_, updated = self._data_layer.update_relationship(json_data,
                                                             model_relationship_field,
                                                             related_id_field,
                                                             kwargs)

        status_code = 200
        result = {'meta': {'message': 'Relationship successfully updated'}}

        if updated is False:
            result = ''
            status_code = 204

        final_result = self.after_patch(result, status_code)

        return final_result
1122309
def update(self, document_id, update_spec, namespace, timestamp):
        
        # Commit outstanding changes so that the document to be updated is the
        # same version to which the changes apply.
        self.commit()
        # Need to escape special characters in the document_id.
        document_id = ''.join(map(
            lambda c: '\\' + c if c in ESCAPE_CHARACTERS else c,
            u(document_id)
        ))

        query = "%s:%s" % (self.unique_key, document_id)
        results = self.solr.search(query)
        if not len(results):
            # Document may not be retrievable yet
            self.commit()
            results = self.solr.search(query)
        # Results is an iterable containing only 1 result
        for doc in results:
            # Remove metadata previously stored by Mongo Connector.
            doc.pop('ns')
            doc.pop('_ts')
            updated = self.apply_update(doc, update_spec)
            # A _version_ of 0 will always apply the update
            updated['_version_'] = 0
            self.upsert(updated, namespace, timestamp)
            return updated
810548
def update(self, resource, resource_id, data):
        '''
        
        '''
        service_def, resource_def, path = self._get_service_information(
            resource)

        update_path = "{0}{1}/" . format(path, resource_id)
        return self.call(path=update_path, data=data, method='patch')
462647
def update(self, request, _id):
        
        _id = deserialize(_id)

        to_update = self.collection.find_one({'_id': _id})
        if to_update:
            document = self.collection(dict(to_update, **request.json))
            document.updated_at = datetime.utcnow()

            updated = document.update()
            return Response(
                response=serialize(updated),
                status=(
                    200 if not all(
                        key in updated for key in [
                            'error_code', 'error_type', 'error_message'
                        ]
                    ) else 400
                )
            )
        else:
            return Response(
                response=serialize(
                    DocumentNotFoundError(self.collection.__name__, _id)
                ),
                status=400
            )
1033215
function(userId, properties, callback) {
      if (!userId) return callback(new Error(utils.i18n.identities.id));
      utils.debug('Identity edit: ' + userId);

      request.patch({
        path: '/users/' + userId + '/identity',
        body: Object.keys(properties).map(function(propertyName) {
          return {
            operation: 'set',
            property: propertyName,
            value: properties[propertyName]
          };
        })
      }, callback || utils.nop);
    }
425446
def patch(self, request, *args, **kwargs):
        
        with reversion.create_revision():
            reversion.set_user(request.user)
            reversion.set_comment('changed through the RESTful API from ip %s' % request.META['REMOTE_ADDR'])
            kwargs['partial'] = True
            return self.update(request, *args, **kwargs)
1353296
def update_urls(self, request, resource_name=None, ids=None):
        
        http_host = request.META.get('HTTP_HOST', None)

        if http_host is None:
            http_host = request.META['SERVER_NAME']
            if request.META['SERVER_PORT'] not in ('80', '443'):
                http_host = "{}:{}".format(
                    http_host, request.META['SERVER_PORT'])

        self.base_url = "{}://{}".format(
            request.META['wsgi.url_scheme'],
            http_host
        )
        self.api_url = "{}{}".format(self.base_url, request.path)
        self.api_url = self.api_url.rstrip("/")

        if ids is not None:
            self.api_url = self.api_url.rsplit("/", 1)[0]

        if resource_name is not None:
            self.api_url = self.api_url.rsplit("/", 1)[0]
112190
def patch(self, endpoint, json=None, params=None, **kwargs):
        
        json = kwargs['data'] if 'data' in kwargs else json
        return self._make_request('patch', endpoint, data=json, params=params)
975924
def _update(self, sock_info, criteria, document, upsert=False,
                check_keys=True, multi=False, manipulate=False,
                write_concern=None, op_id=None, ordered=True,
                bypass_doc_val=False, collation=None, array_filters=None,
                session=None, retryable_write=False):
        """"""
        common.validate_boolean("upsert", upsert)
        if manipulate:
            document = self.__database._fix_incoming(document, self)
        collation = validate_collation_or_none(collation)
        write_concern = write_concern or self.write_concern
        acknowledged = write_concern.acknowledged
        update_doc = SON([('q', criteria),
                          ('u', document),
                          ('multi', multi),
                          ('upsert', upsert)])
        if collation is not None:
            if sock_info.max_wire_version < 5:
                raise ConfigurationError(
                    'Must be connected to MongoDB 3.4+ to use collations.')
            elif not acknowledged:
                raise ConfigurationError(
                    'Collation is unsupported for unacknowledged writes.')
            else:
                update_doc['collation'] = collation
        if array_filters is not None:
            if sock_info.max_wire_version < 6:
                raise ConfigurationError(
                    'Must be connected to MongoDB 3.6+ to use array_filters.')
            elif not acknowledged:
                raise ConfigurationError(
                    'arrayFilters is unsupported for unacknowledged writes.')
            else:
                update_doc['arrayFilters'] = array_filters
        command = SON([('update', self.name),
                       ('ordered', ordered),
                       ('updates', [update_doc])])
        if not write_concern.is_server_default:
            command['writeConcern'] = write_concern.document

        if not sock_info.op_msg_enabled and not acknowledged:
            # Legacy OP_UPDATE.
            return self._legacy_write(
                sock_info, 'update', command, op_id,
                bypass_doc_val, message.update, self.__full_name, upsert,
                multi, criteria, document, False, write_concern.document,
                check_keys, self.__write_response_codec_options)

        # Update command.
        if bypass_doc_val and sock_info.max_wire_version >= 4:
            command['bypassDocumentValidation'] = True

        # The command result has to be published for APM unmodified
        # so we make a shallow copy here before adding updatedExisting.
        result = sock_info.command(
            self.__database.name,
            command,
            write_concern=write_concern,
            codec_options=self.__write_response_codec_options,
            session=session,
            client=self.__database.client,
            retryable_write=retryable_write).copy()
        _check_write_command_response(result)
        # Add the updatedExisting field for compatibility.
        if result.get('n') and 'upserted' not in result:
            result['updatedExisting'] = True
        else:
            result['updatedExisting'] = False
            # MongoDB >= 2.6.0 returns the upsert _id in an array
            # element. Break it out for backward compatibility.
            if 'upserted' in result:
                result['upserted'] = result['upserted'][0]['_id']

        if not acknowledged:
            return None
        return result
430883
def patchURL(self, url, headers, body):
        
        return self._load_resource("PATCH", url, headers, body)
778308
def patch(self, service, path, body, **kwargs):
        
        return self.make_request(Methods.PATCH, service, path, body=body,
                                 **kwargs)
1110614
def replace_entity_resource(model, oldres, newres):
    '''
    
    '''
    oldrids = set()
    for rid, link in model:
        if link[ORIGIN] == oldres or link[TARGET] == oldres or oldres in link[ATTRIBUTES].values():
            oldrids.add(rid)
            new_link = (newres if o == oldres else o, r, newres if t == oldres else t, dict((k, newres if v == oldres else v) for k, v in a.items()))
            model.add(*new_link)
    model.delete(oldrids)
    return
1180496
private Status update(Database _db, String docID, Body body, boolean deleting) {
        Status status = new Status();

        if (docID != null && docID.isEmpty() == false) {
            // On PUT/DELETE, get revision ID from either ?rev= query or doc body:
            String revParam = getQuery("rev");
            String ifMatch = getRequestHeaderValue("If-Match");
            if (ifMatch != null) {
                if (revParam == null)
                    revParam = ifMatch;
                else if (!ifMatch.equals(revParam))
                    return new Status(Status.BAD_REQUEST);
            }
            if (revParam != null && body != null) {
                String revProp = (String) body.getProperties().get("_rev");
                if (revProp == null) {
                    // No _rev property in body, so use ?rev= query param instead:
                    body.getProperties().put("_rev", revParam);
                    //body = new Body(bodyDict);
                } else if (!revParam.equals(revProp)) {
                    throw new IllegalArgumentException("Mismatch between _rev and rev");
                }
            }
        }

        RevisionInternal rev = update(_db, docID, body, deleting, false, status);
        if (status.isSuccessful()) {
            cacheWithEtag(rev.getRevID());  // set ETag
            if (!deleting) {
                URL url = connection.getURL();
                String urlString = url.toExternalForm();
                if (docID != null) {
                    urlString += '/' + rev.getDocID();
                    try {
                        url = new URL(urlString);
                    } catch (MalformedURLException e) {
                        Log.w("Malformed URL", e);
                    }
                }
                setResponseLocation(url);
            }
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("ok", true);
            result.put("id", rev.getDocID());
            result.put("rev", rev.getRevID());
            connection.setResponseBody(new Body(result));
        }
        return status;
    }