def update(x): if x == "REAL": k.update_one({ "_id": ObjectId("5ee46d8088b3ec0144d5801b") }, {'$inc':{'num_real':1}}) elif x == "FAKE": k.update_one({ "_id": ObjectId("5ee46d8088b3ec0144d5801b") }, {'$inc':{'num_fake':1}}) elif x == "CLICKBAIT": k.update_one({ "_id": ObjectId("5ee4d1691850cb02c0edc4cc") }, {'$inc':{'num_clickbait':1}}) elif x == "NOT CLICKBAIT": k.update_one({ "_id": ObjectId("5ee4d1691850cb02c0edc4cc") }, {'$inc':{'num_notclickbait':1}})
def put(self, jobinstance_id): """ Edit the participants in a job instance """ request_data = JobInstance.parser.parse_args() try: with mongo.cx.start_session() as session: with session.start_transaction(): job_instance = JobInstanceModel.find_by_id(jobinstance_id) participants = [] if not job_instance: return { "message": "A job instance with that ID does not exist" }, 404 if job_instance["is_approved"]: return {"message": "already approved"}, 400 if not request_data["participant_ids"]: return { "message": "A job instance must have participants" }, 400 for participant_id in request_data["participant_ids"]: profile = ProfilesModel.find_by_id(participant_id) if not profile: return { "message": f"Participant {participant_id} not found in database" } participants.append(profile) # Updating the job instance job_instance["participant_ids"] = [ ObjectId(participant_id) for participant_id in request_data["participant_ids"] ] mongo.db.jobinstances.update( {"_id": ObjectId(jobinstance_id)}, job_instance) job_instance["participants"] = participants job_instance["job"] = JobsModel.find_by_id( job_instance["job_id"]) return strip_objectid(job_instance) except ValidationError as error: return {"message": error.message}, 400 except Exception as error: traceback.print_exc(error) return {"message": "unknown error"}, 500
def get_data(x): a = k.find({"_id": ObjectId("5ee46d8088b3ec0144d5801b")})[0] b = k.find({"_id": ObjectId("5ee4d1691850cb02c0edc4cc")})[0] if x == "FAKE": return (a['num_fake']) elif x == "REAL": return (a['num_real']) elif x == "CLICKBAIT": return (b['num_clickbait']) elif x == "NOT CLICKBAIT": return (b['num_notclickbait']) else: return "INVALID"
def delete(self, recipe_id): recipe = RecipesModel.find_by_id(recipe_id) image_id = recipe['image_id'] if not recipe: return {"message": "A recipe with this name does not exist"} # Using a transaction to ensure image & recipe both delete or neither does with mongo.cx.start_session() as session: with session.start_transaction(): mongo.db.recipes.remove({"_id": ObjectId(recipe_id)}) mongo.db.images.remove({"_id": ObjectId(image_id)}) return {"message": "Recipe deleted"}, 200
def get_links(): try: pipeline = [ {"$match": {"Type": "Não avaliado"}}, {"$sample": {"size": 1}} ] with articleDB('News') as adb: result = adb.aggregate(pipeline) for article in result: with articleDB('News') as adb: adb.update_one({'_id': ObjectId(article['_id'])}, { "$set": {"Type": "Em avaliação"}}) data = { 'id_': str(article['_id']), 'article': article['Article'], 'title': article['Title'], 'subtitle': article['SubTitle'], 'date': article['Date'], 'link': article['Link'] } return make_response(jsonify(data), 200) return make_response(jsonify(None), 504) except Exception as e: return make_response(jsonify('Unexpected error.\n{}'.format(str(e))), 500)
def post(self, request, template_id=None): data = Q2D_POST(request) if template_id: Template().update({"_id": ObjectId(template_id)}, data) return Response({"result": True}) Template(data).save() return Response({"result": True})
def post(self, request, taskflow_id=None): data = Q2D_POST(request) data['create_time'] = time.strftime("%Y-%m-%d %H:%M:%S") data['is_deleted'] = False data['is_finished'] = False data['is_started'] = False data['start_time'] = None taskflow_id = Taskflow(data).save()[0] taskflow = Taskflow().get_one({"_id": ObjectId(taskflow_id)}) taskflow['id'] = taskflow_id taskflow['resource_uri'] = "/api/v3/taskflow/%s/" % taskflow['id'] taskflow['instance_id'] = taskflow['_id'] taskflow['business'] = { "always_use_executor": True, "cc_company": "", "cc_id": 2, "cc_name": "蓝鲸", "cc_owner": "", "executor": "admin", "id": 1, "life_cycle": "2", "resource_uri": "/o/bk_sops/api/v3/business/2/", "time_zone": "Asia/Shanghai" } return Response(taskflow)
def get(self, request, template_id=None): if template_id: return Response(Template().get_one({"_id": ObjectId(template_id)})) templates = Template().get_all() data = [] for template in templates: data.append({ "category": "Other", "edit_time": "2018-04-23 17:30:48 +0800", "create_time": "2018-04-23 17:26:40 +0800", "name": template.get("name"), "bk_biz_id": "2", "creator": "admin", "bk_biz_name": "蓝鲸", "id": template.get('_id'), "editor": "admin" }) return Response({ "result": True, "objects": data, "meta": { "total_count": len(templates) } })
def delete(self, identifier): """Deletes an existing feature :param identifier: feature id """ self.featuredb[self.collection].delete_one( {'_id': ObjectId(identifier)})
def update(self, _id, data): if not self.exists(_id): abort(404) data = self.validate(data, _id=_id) self.collection.find_one_and_update({'_id': ObjectId(_id)}, {'$set': data}) return self.retrieve(_id)
def download_and_deliver(self, user): try: user: User = jsonpickle.loads(user, classes=[User, User.REMOVED, Schedule]) # Clear user db entry and downloads file_manager.remove_schedule(user.uid) if file_manager.does_path_exist( file_manager.get_user_download_path(user.uid)): file_manager.delete_user_file(user.uid) path = '' if user.deliver_voicenote: path = file_manager.download_user_file(user) # Update/create database entry for logging and management logger.debug('Scheduled time: %s' % user.REMOVED.scheduled_date) schedule_id = file_manager.create_db_schedule(user, path) schedule = file_manager.downloads_collection.find_one( {"_id": ObjectId(schedule_id)}) schedule = Schedule(user, schedule['path']) user_json = jsonpickle.dumps(user) schedule_json = jsonpickle.dumps(schedule) deliver.apply_async(args=[user_json, schedule_json], queue='deliver') return user, schedule except SoftTimeLimitExceeded as e: self.retry(exc=e)
def test_two_same_recommendations_are_created(integration_db, mocker): """No duplicate error is raised""" from pymongo.collection import ObjectId res = integration_db.mst_food_ingredients.insert_one({ 'name': 'flax', 'created_at': datetime.now().isoformat(), 'updated_at': datetime.now().isoformat(), }) integration_db.patient_ingredient_recommendation.insert_one({ 'patient_id': ObjectId('5cab584074e88f0cb0977a08'), 'ingredient_id': res.inserted_id, 'type': "min", 'quantity': 0, 'created_at': datetime.now().isoformat(), 'updated_at': datetime.now().isoformat(), }) mocker.patch( 'saana_lib.patient.MinimizeIngredients.all', new_callable=mocker.PropertyMock, return_value={"flax": 0} ) _ = MinimizeRecommendation(obj_id().__str__()).to_db() assert integration_db.patient_ingredient_recommendation.estimated_document_count() == 2 assert integration_db.patient_ingredient_recommendation.find_one()['type'] == 'min'
def validate(self, data, _id=None): """ When creating or updating an object. This method validates the inputs :param data: data to validate :type data: dict :param _id: ID as a string, or None in case of new objects :type _id: str or None :rtype: dict """ if self.unique: query = {self.name: data} if _id: """ If object is being updated, the query is adjusted to exclude the object being updated (otherwise, it isn't possible to save an object without changing the unique field values every time) """ query['_id'] = {'$not': {'$eq': ObjectId(_id)}} if self.model.collection.find(query).count() > 0: raise ValidationError('%s with this %s already exists' % (self.model.name, self.name), field=self.name) return data
def test_all_ingredients_recommendation(integration_db): from tests.conftest import PATIENT, ObjectId AllRecommendations(PATIENT['_id'].__str__()).store() assert integration_db.patient_ingredient_recommendation.estimated_document_count() == 13 assert integration_db.patient_ingredient_recommendation.find_one( {'ingredient_id': ObjectId('6f4ec514eee84cc58c8e610a')} )['type'] == 'avoid'
def post(self, jobinstance_id): """ Endpoint to approve a job instance where no edit required """ try: with mongo.cx.start_session() as session: with session.start_transaction(): job_instance = JobInstanceModel.find_by_id(jobinstance_id) if not job_instance: return { "message": "A job instance with that ID does not exist" }, 404 # Update JOBINSTANCE if job_instance["is_approved"]: return {"message": "already approved"}, 400 job_instance["is_approved"] = True mongo.db.jobinstances.update( {"_id": ObjectId(jobinstance_id)}, job_instance) # Update PROFILES job_id = str(job_instance["job_id"]) job = JobsModel.find_by_id(job_id) for profile_id in job_instance["participant_ids"]: updated_profile = ProfilesModel.find_by_id(profile_id) # Completed Jobs if job_id in updated_profile["completed_jobs"]: updated_profile["completed_jobs"][job_id][ "number_completed_instances"] += 1 else: updated_profile["completed_jobs"][job_id] = { "job_name": job["name"], "number_completed_instances": 1 } # Money Owed updated_profile["money_owed"] += job["reward"] # Total_money_earned updated_profile["total_money_earned"] += job["reward"] print(updated_profile) mongo.db.profiles.update({"_id": profile_id}, updated_profile) return strip_objectid(job_instance) except Exception as error: traceback.print_exc(error) return {"message": "unknown error"}, 500 return "foo bar"
def exists(self, _id): """ Check to see if a document with a given ID exists :param _id: the id to check :type _id: str :rtype: bool """ return self.collection.find({'_id': ObjectId(_id)}).count() == 1
def update(self, identifier, updated_feature): """Updates an existing feature id with new_feature :param identifier: feature id :param new_feature: new GeoJSON feature dictionary """ data = {k: v for k, v in updated_feature.items() if k != 'id'} self.featuredb[self.collection].update_one( {'_id': ObjectId(identifier)}, {"$set": data})
def delete(self, profile_id): """ Delete a specific profile """ profile = ProfilesModel.find_by_id(profile_id) if profile is None: return {"message": "A profile with that ID does not exist"} mongo.db.profiles.remove({"_id": ObjectId(profile_id)}) return {"message": "Profile has been deleted"}
def Q2D_POST(request): _data = {} try: d = json.loads(request.body) if isinstance(d, list): return d for key in d: if key == "_id": value = ObjectId(d[key]) _data[key] = value else: _data[key] = d[key] except: d = request.POST.items() for key, value in d: if key == "_id": value = ObjectId(value) _data[key] = value return _data
def symptoms_progress_test_db(integration_db): patient_id = ObjectId('5cabf2ad37c87f3ac00e8701') symptom_id_1 = ObjectId('5cab584074e88f0cb0977a0f') symptom_id_2 = ObjectId('5cabf2ad37c87f3ac00e870d') integration_db.patient_symptoms.insert_many([ { 'symptom_id': symptom_id_1, 'created_at': datetime(2019, 4, 2, 1), 'updated_at': datetime(2019, 4, 2, 1), 'patient_id': patient_id, 'symptoms_scale': 3 }, { 'symptom_id': symptom_id_2, 'created_at': datetime(2019, 3, 12, 1), 'updated_at': datetime(2019, 3, 12, 1), 'patient_id': patient_id, 'symptoms_scale': 5 }, { 'symptom_id': symptom_id_1, 'created_at': datetime(2019, 10, 10, 1), 'updated_at': datetime(2019, 10, 10, 1), 'patient_id': patient_id, 'symptoms_scale': 8 }, { 'symptom_id': symptom_id_2, 'created_at': datetime(2019, 7, 20, 1), 'updated_at': datetime(2019, 7, 20, 1), 'patient_id': patient_id, 'symptoms_scale': 1 }, { 'symptom_id': symptom_id_1, 'created_at': datetime(2019, 5, 15, 1), 'updated_at': datetime(2019, 5, 15, 1), 'patient_id': patient_id, 'symptoms_scale': 2 }, ]) yield patient_id, symptom_id_1, symptom_id_2 integration_db.patient_symptoms.drop()
def __init__(self, _collection: MongoCollection, _id: object = None): """Create a bind post using a mongo collection and a post id.""" self._collection: MongoCollection = _collection if _id: self._id = _id else: self._id = ObjectId() if not self._dict: d = dict(_id=self._id) self._collection.insert_one(d)
def get(self, identifier): """ query the provider by id :param identifier: feature id :returns: dict of single GeoJSON feature """ featurelist, matchcount = self._get_feature_list( {'_id': ObjectId(identifier)}) return featurelist[0] if featurelist else None
def delete(self, jobinstance_id): """ Delete a specific job instance """ jobinstance = JobInstanceModel.find_by_id(jobinstance_id) if jobinstance is None: return {"message": "Job instance has already been deleted"} mongo.db.jobinstances.remove({"_id": ObjectId(jobinstance_id)}) return {"message": "Job instance deleted"}
def get_original(self, _id): """ Helper function that returns the original value of the object, before it is updated. If you want to leave a value unchanged on update, the `.set()` method should call and return this function (otherwise the field value will be set to `None`) :param _id: the object id as a string """ obj = self.model.to_repr(_id=ObjectId(_id))[0] return obj[self.name]
def set_access_token(self, user: UserLogin) -> bool: self.__logger.info( f"Setting new access token for user: {user.user_id}") update_user = {"_id": ObjectId(user.user_id)} update_data = {"$set": {"access_token": user.access_token}} updated_data = self.__user_collection.update_one( update_user, update_data) return updated_data.raw_result['updatedExisting']
def evaluate(request): if is_json(request): data, err = EvaluationSchema().load(request.json) if err: return HTTPBadRequest() videos = request.db['videos'] if data['positive']: videos.find_and_modify({'_id': ObjectId(data['_id'])}, {'$inc': { 'likes': 1 }}) return HTTPOk() videos.find_and_modify({'_id': ObjectId(data['_id'])}, {'$inc': { 'dislikes': 1 }}) return HTTPOk() return HTTPForbidden()
def put(self, recipe_id): request_data = request.json old_recipe = RecipesModel.find_by_id(recipe_id) if not old_recipe: return {"message": "A Recipe with that ID does not exist"} try: # Using a transaction to ensure image & recipe both update or neither does with mongo.cx.start_session() as session: with session.start_transaction(): updated_recipe = RecipesModel.build_recipe_from_request( request_data) # If key exists in a dictionary (If new image) if 'image_data' in request_data: mongo.db.images.remove( {"_id": ObjectId(old_recipe['image_id'])}) image_data = b64decode(request_data['image_data']) image_content_type = request_data['image_content_type'] built_image = ImageModel.build_image( image_data, image_content_type) result = mongo.db.images.insert_one(built_image) updated_recipe['image_id'] = str(result.inserted_id) else: # If we want the origional image updated_recipe['image_id'] = old_recipe['image_id'] mongo.db.recipes.update({"_id": ObjectId(recipe_id)}, updated_recipe) updated_recipe['_id'] = recipe_id return RecipesModel.return_as_object(updated_recipe) except ValidationError as error: return {"message": error.message}, 400
def avaliate_links(): try: _id = request.form['_id'] status = request.form['status'] print(75*'#') print("- Id: ObjectID('{0}')".format(_id)) print('- Status', status) except KeyError as e: return make_response(jsonify('Missing key'), 400) except Exception as e: return make_response(jsonify('Unexpected error.\n{}'.format(str(e))), 500) try: if status == '1': with articleDB('News') as adb: adb.update_one({"_id": ObjectId(_id)}, { "$set": {"Type": "Bom"}}) elif status == '2': with articleDB('News') as adb: adb.update_one({"_id": ObjectId(_id)}, { "$set": {"Type": "Ruim"}}) elif status == '4': with articleDB('News') as adb: adb.update_one({"_id": ObjectId(_id)}, { "$set": {"Type": "Não avaliado"}}) elif status == '5': with articleDB('News') as adb: adb.update_one({"_id": ObjectId(_id)}, { "$set": {"Type": "Não avaliado"}}) else: with articleDB('News') as adb: adb.update_one({"_id": ObjectId(_id)}, { "$set": {"Type": "Sem valor"}}) return make_response(jsonify(None), 204) except Exception as e: return make_response(jsonify('Unexpected error.\n{}'.format(str(e))), 500)
def post(self, request, business_id=None): data = Q2D_POST(request) template = Template().get_one( {"_id": ObjectId(data.get("template_id"))}) return Response({ "result": True, "data": { "constants_not_referred": {}, "pipeline_tree": json.loads(template.get('pipeline_tree')) } })
def delete(self, job_id): """ Delete a specific job """ job = JobsModel.find_by_id(job_id) if job is None: return {"message": "A job with that ID does not exist"} # TODO: remove job from user profile once it has been deleted mongo.db.jobs.remove({"_id": ObjectId(job_id)}) return {"message": "Job has been deleted"}