def delete(self, request, *args, **kw): # deletes table db_id = request.data.get("db_id", None) table_id = request.data.get("table_id", None) access_token = request.META.get("HTTP_ACCESS_TOKEN", None) result = {} result[RESPONSE_STATUS] = RESPONSE_STATUS_ERROR if db_id and ObjectId.is_valid(db_id) and access_token: mainDB = getDatabase() token = mainDB.tokens.find_one({"token": access_token}) if mainDB else None if token and access_token_valid(token): if mainDB: result[RESPONSE_STATUS] = RESPONSE_STATUS_SUCCESS if table_id: if ObjectId.is_valid(table_id): result[DELETED_TABLE_COUNT] = mainDB.tables.delete_one( {"_id": ObjectId(table_id), "author": token["author"], "database_id": ObjectId(db_id)} ).deleted_count else: result[RESPONSE_STATUS] = RESPONSE_STATUS_ERROR result[RESPONSE_STATUS_ERROR_MSG] = TABLE_ID_INVALID else: result[DELETED_TABLE_COUNT] = mainDB.tables.delete_many( {"author": token["author"], "database_id": ObjectId(db_id)} ).deleted_count else: result[RESPONSE_STATUS_ERROR_MSG] = MASTER_DB_UNINITIALIZED else: result[RESPONSE_STATUS_ERROR_MSG] = ACCESS_TOKEN_INVALID else: result[RESPONSE_STATUS_ERROR_MSG] = TOKEN_MISSING if not access_token else DATABASE_ID_INVALID response = Response(result, status=status.HTTP_200_OK) return response
def _updateStartingPanelID(self, comicID, firstPanelID): """This is a private method. Add the firstPanelID to the given comic as the starting panel, return true if successful, false otherwise""" if (not ObjectId.is_valid(comicID)) or (not ObjectId.is_valid(firstPanelID)): return False if (self.comicsCollection.find_and_modify({self.idField: ObjectId(comicID)}, {"$set" : {self.firstPanelIDField : firstPanelID} }) != None): return True return False # update unsuccessful
def update_mirroring(frame_id, mirroring_id): """ Set a frame to mirror another by id """ fid = frame_id if not ObjectId.is_valid(frame_id) else ObjectId(frame_id) mid = frame_id if not ObjectId.is_valid(mirroring_id) else ObjectId(mirroring_id) doc = {"mirroring": mid} resp = Frames.collection.find_one_and_update({"_id": fid}, {"$set": doc}, return_document=ReturnDocument.AFTER) return _unify_ids(resp)
def test_is_valid(self): self.assertFalse(ObjectId.is_valid(None)) self.assertFalse(ObjectId.is_valid(4)) self.assertFalse(ObjectId.is_valid(175.0)) self.assertFalse(ObjectId.is_valid({"test": 4})) self.assertFalse(ObjectId.is_valid(["something"])) self.assertFalse(ObjectId.is_valid("")) self.assertFalse(ObjectId.is_valid("12345678901")) self.assertFalse(ObjectId.is_valid("1234567890123")) self.assertTrue(ObjectId.is_valid(b("123456789012"))) self.assertTrue(ObjectId.is_valid("123456789012123456789012"))
def update_artifact_by_id(self,collection,artifact_id,field=None,value=None,document=None): if document: #Careful, this replaces the document entirely if ObjectId.is_valid(artifact_id): self.c[collection].update({"_id":ObjectId(artifact_id)}, document) else: self.c[collection].update({"_id":artifact_id}, document) elif field and value: if ObjectId.is_valid(artifact_id): self.c[collection].update({"_id":ObjectId(artifact_id)}, {"$set" : {field:value}}) else: self.c[collection].update({"_id":artifact_id}, {"$set" : {field:value}}) else: raise WrongParametersExecption
def add_item_to_artifact_set(self,collection,artifact_id,field,value): self.init_artifact_set(collection,artifact_id,field,[]) if ObjectId.is_valid(artifact_id): self.c[collection].update({"_id":ObjectId(artifact_id)},{"$addToSet":{field: value}}) else: self.c[collection].update({"_id":artifact_id},{"$addToSet":{field: value}}) self.update_artifact_state(collection, artifact_id)
def put(self, id): """ Update slide information --- tags: - Slide parameters: - in: path name: id description: MonogDB ObjectId -- Example 57bf3c092f9b2e1595b29730 type: string - in: body name: json description: JSON object containing parameters to update type: string responses: 200: description: Returns the slide information 404: description: Invalid slide Id or slide not found """ if not ObjectId.is_valid(id): resp = {"status": 404, "message": "Invalid slide Id " + id} return Response(dumps(resp), status=404, mimetype="application/json") image = self.slides.find_one({"_id": ObjectId(id)}, {"scanProperties": False}) if image: self.slides.update_one({"_id": ObjectId(id)}, {"$set": request.get_json(force=True)}) image = self.slides.find_one({"_id": ObjectId(id)}, {"scanProperties": False}) image["id"] = str(image["_id"]) return Response(dumps(image), status=200, mimetype="application/json") else: return Response("", status=404, mimetype="application/json")
def get(self, entity_id, chart_id): if not ObjectId.is_valid(chart_id): self.set_status(httplib.BAD_REQUEST) raise Return() if entity_id not in ICON_ENTITIES: self.set_status(httplib.NOT_FOUND) raise Return() chart = yield Query(self.settings["database"], entity_id.capitalize()).find_one({"_id": ObjectId(chart_id)}) if chart is None: self.set_status(httplib.NOT_FOUND) raise Return() icon_data, last_updated = self._get_chart_icon(chart) modified_since = self.request.headers.get(resources.IF_MODIFIED_HEADER) if modified_since is not None and last_updated == modified_since: self.set_status(httplib.NOT_MODIFIED) accept = self.request.headers.get(resources.ACCEPT_HEADER) if accept is not None and accept.lower() == resources.SVG_CONTENT_TYPE: icon = icon_data content_type = resources.SVG_CONTENT_TYPE else: icon = cairosvg.svg2png(icon_data) content_type = resources.PNG_CONTENT_TYPE self.add_header(resources.CONTENT_TYPE_HEADER, content_type) self.add_header(resources.CACHE_CONTROL, resources.CACHE_CONTROL_NO_CACHE) self.write(icon)
def get(self, id): """ Get deep zoom image --- tags: - Deep Zoom parameters: - in: path name: id description: MonogDB ObjectId -- Example 57bf3c092f9b2e1595b29730 type: string responses: 200: description: Returns the slide information 404: description: Invalid slide Id or slide not found """ if not ObjectId.is_valid(id): resp = {"status": 404, "message": "Invalid slide Id " + id} return Response(dumps(resp), status=404, mimetype='application/json') image = self.slides.find_one({'_id': ObjectId(id)}) path = image["path"] slide = get_slide(path) if slide == None: Response("", status=404, mimetype='application/xml') else: return Response(slide.get_dzi(self.config['deepzoom_format']), status=200, mimetype='application/xml')
def update_by_id(user_id, doc): """ Update user by id, returning the updated doc """ cid = user_id if not ObjectId.is_valid(user_id) else ObjectId(user_id) return Users.collection.find_one_and_update( {"_id": cid}, {"$set": doc}, return_document=ReturnDocument.AFTER)
def load_document(self, bucket, doc_id): if not doc_id: raise Exception('Need a doc_id to load a document') if ObjectId.is_valid(doc_id): doc_id = ObjectId(doc_id) handle = self.handle(bucket) return handle.find_one(doc_id)
def delete_by_id(frame_id): """ Update a frame by id, returning the updated doc """ fid = frame_id if not ObjectId.is_valid(frame_id) else ObjectId(frame_id) resp = Frames.collection.delete_one({"_id": fid}) return _unify_ids(resp)
def get_email_or_404(id_str): if not ObjectId.is_valid(id_str): raise ObjectDoesNotExist() email = Email.find_one({'_id': ObjectId(id_str)}) if not email: raise ObjectDoesNotExist() return email
def todo_delete(id): if ObjectId.is_valid(id): result = todos.delete_one({'_id': ObjectId(id)}) if result.deleted_count > 0: return jsonify({'result': 'Successfully removed ' + id}) return not_found()
def todo_get(id): if ObjectId.is_valid(id): todo = todos.find_one({'_id': ObjectId(id)}) if todo: return jsonify(todo) return not_found()
def get_resource_or_404(id_str): if not ObjectId.is_valid(id_str): raise ObjectDoesNotExist() id = ObjectId(id_str) if not gfs.exists(id): raise ObjectDoesNotExist() return gfs.get(id)
def delData(request,res,db): ''' Desc: fetch all data about the user Args: request: request with different data res: result that we need to update and return Err: 1. invalid objectId 2. fail to delete data ''' # error handler for invalid objectid if not ObjectId.is_valid(res["uid"]): res["err"]["status"] = 1 res["err"]["msg"] = "wrong id" return res data = {"_id":ObjectId(res["uid"])} # data = {"sid":{"$in":schedule_list}} docs = db.removeData(data) # error handler for getting data if docs["status"]: res["err"] = docs return res # # normal process # return res
def delData(request,res,db): ''' Desc: delete the schedule exercise by id Args: request: maybe useful res: id stores in res["sid"], and update res with proper information Err: 1. invalid objectId 2. fail to delete data ''' # error handler for invalid objectid if not ObjectId.is_valid(res["sid"]): res["err"]["status"] = 1 res["err"]["msg"] = "wrong id" return res data = {"_id":ObjectId(res["sid"])} # data = {"sid":{"$in":schedule_list}} docs = db.removeData(data) # error handler for getting data if docs["status"]: res["err"] = docs return res # # normal process # res["content"]["status"] = "successful" return res
def get_by_id(user_id): """ Get user by id """ cid = user_id if not ObjectId.is_valid(user_id) else ObjectId(user_id) return Users.collection.find_one({'_id': cid}, projection=Users.default_projection)
def edit_post(post_id): form = PostEditForm(request.form) if not ObjectId.is_valid(post_id): abort(404) post = Post.objects(id=post_id).first() if post is None: abort(404) if not post.can_edit(current_user): abort(403) topic = post.topic board = topic.board forum = post.forum if request.method == "POST" and form.validate(): post_edit = PostEdit(author=current_user.to_dbref(), content=form.content.data, date=datetime.utcnow()) post.edits.append(post_edit) post.content = form.content.data post.save() return redirect(topic.get_url()) form.content.data = post.content return render_template("forum_post_edit.html", form=form, topic=topic, board=board, forum=forum)
def putData(request,res,db): ''' Desc: update some fields of a schedule exercise Args: request: store the updated information of exercise within request.form db: referrence to db object res: store the status Err: 1. fail to update data ''' if not ObjectId.is_valid(res["sid"]): #res["err"]["status"] = 1 #res["err"]["msg"] = "wrong id" #return res match_data = {"sid":int(res["sid"])} else: match_data = {"_id":ObjectId(res["sid"])} docs = db.updateData(match_data,request.form) # catch the error of updating if docs["status"]: res["err"] = docs return res # return the status res["content"]["status"] = docs["status"] return res
def handleSellMaterial(self, rqst, owner): ses = self.sessions.get(owner, None) if ses != None: try: pid = ObjectId(rqst.data['pid']) if not ObjectId.is_valid(pid): return matData = self.database.fetchPlayerItemData(pid)['Material'] price = 0 for i in matData: for j in rqst.data['mat']: if j['type'] == i['type'] and j['level'] == i['level']: if j['count'] > i['count']: return else: price += self.getMaterialSetting(j['type'], j['level'])[1] * j['count'] i['count'] -= j['count'] # remove whose count is 0: rev = range(len(matData)) rev.reverse() for i in rev: if matData[i]['count'] == 0: del matData[i] if price == rqst.data['price']: pprop = self.database.fetchPlayerProperty(pid) pprop['Coins'] = pprop['Coins'] + price self.database.updatePlayerProperty(pid, pprop) self.database.updatePlayerMaterial(pid, matData) except: print '%d sell material failed'%(owner)
def approveUser(ID, accept): if not ObjectId.is_valid(ID): return False if ID == str(session['user']['_id']): return False result = db.users.update_one({'_id' : ObjectId(ID), 'confirmed' : True, 'clinic' : session['user']['clinic']}, {'$set' : {'approved' : accept}}) if result.modified_count == 1 or accept == False: info = db.users.find_one({'_id' : ObjectId(ID)}) if not info: return False #cover all of our bases if accept: userMsg = Message('Account Approved', #app title sender = ('Example Administrator', '*****@*****.**'), recipients = [(info['first'] + ' ' + info['last'], info['email'])]) userMsg.body = template('finalUser.txt', user = info, accept = True) userMsg.html = template('finalUser.html', user = info, accept = True) else: userMsg = Message('Account Removed', #app title sender = ('Example Administrator', '*****@*****.**'), recipients = [(info['first'] + ' ' + info['last'], info['email'])]) userMsg.body = template('finalUser.txt', user = info, accept = False) userMsg.html = template('finalUser.html', user = info, accept = False) deletion = db.users.delete_one({'_id' : ObjectId(ID)}) if deletion.deleted_count == 0: return False mail.send(userMsg) return True #something messed up return False
def update_menu(menu_id): # check if menu_id coming in from URL is a valid ObjectId format if ObjectId.is_valid(menu_id): menu = mongo.db.menus.find_one_or_404({"_id": ObjectId(menu_id)}) else: abort(404) if not request.json: abort(400) if "menu_name" in request.json and type(request.json["menu_name"]) != unicode: abort(400) # update using request json variable, if not present use current one in the db. mongo.db.menus.update( {"_id": ObjectId(menu_id)}, { "$set": { "menu_name": request.json.get("menu_name", menu["menu_name"]), "URL": request.json.get("URL", menu["URL"]), "show_on_nav": request.json.get("show_on_nav", menu["show_on_nav"]), "sort_order": request.json.get("sort_order", menu["sort_order"]), } }, ) return jsonify({"update": "success"})
def put(self, request, *args, **kw): # updates the database db_id = request.GET.get('db_id', None) access_token = request.META.get('HTTP_ACCESS_TOKEN', None) result = {} result[RESPONSE_STATUS] = RESPONSE_STATUS_ERROR if db_id and access_token: mainDB = getDatabase() token = mainDB.tokens.find_one({"token": access_token}) if mainDB else None if token and access_token_valid(token): if ObjectId.is_valid(db_id): database = mainDB.databases.find_one({"author": token["author"], "_id": ObjectId(db_id)}) if database: db_name = request.GET.get('db_name', None) or database["database_name"] db_name = ''.join(db_name.split(' ')).lower() mainDB.databases.update_one( {"_id": ObjectId(db_id), "author": token["author"]}, { "$set": { "database_name": db_name, } } ) result[RESPONSE_STATUS] = RESPONSE_STATUS_SUCCESS result[RESPONSE_STATUS_SUCCESS_MSG] = DATABASE_UPDATED.format(db_name) result[DATABASE_ID] = db_id else: result[RESPONSE_STATUS_ERROR_MSG] = DATABASE_NOT_FOUND else: result[RESPONSE_STATUS_ERROR_MSG] = DATABASE_ID_INVALID else: result[RESPONSE_STATUS_ERROR_MSG] = ACCESS_TOKEN_INVALID else: result[RESPONSE_STATUS_ERROR_MSG] = TOKEN_MISSING if not access_token else DATABASE_ID_INVALID response = Response(result, status=status.HTTP_200_OK) return response
def get(self, request, *args, **kw): # get database details db_id = request.GET.get('db_id', None) access_token = request.META.get('HTTP_ACCESS_TOKEN', None) result = {} result[RESPONSE_STATUS] = RESPONSE_STATUS_ERROR if access_token: mainDB = getDatabase() token = mainDB.tokens.find_one({"token": access_token}) if mainDB else None if token and access_token_valid(token): if mainDB: result[RESPONSE_STATUS] = RESPONSE_STATUS_SUCCESS if db_id: if ObjectId.is_valid(db_id): result[DATABASE_KEY] = dumps(mainDB.databases.find_one({"_id": ObjectId(db_id), "author": token['author']})) else: result[RESPONSE_STATUS] = RESPONSE_STATUS_ERROR result[RESPONSE_STATUS_ERROR_MSG] = DATABASE_ID_INVALID else: result[DATABASE_KEY] = dumps(mainDB.databases.find({"author": token['author']})) else: result[RESPONSE_STATUS_ERROR_MSG] = MASTER_DB_UNINITIALIZED else: result[RESPONSE_STATUS_ERROR_MSG] = ACCESS_TOKEN_INVALID else: result[RESPONSE_STATUS_ERROR_MSG] = TOKEN_MISSING response = Response(result, status=status.HTTP_200_OK) return response
def getClinicName(ID): if not ObjectId.is_valid(ID): return None #do we want a more human-readable clinic code in the future? #this is good because we don't need to f**k with autoincrement clinic = db.clinics.find_one({'_id' : ObjectId(ID)}) if clinic: return clinic['name'] return None
def _search(self, query, search_term): # TODO: Unfortunately, MongoEngine contains bug which # prevents running complex Q queries and, as a result, # Flask-Admin does not support per-word searching like # in other backends op, term = parse_like_term(search_term) criteria = None for field in self._search_fields: flt = {} if isinstance(field, (mongoengine.base.fields.ObjectIdField)): if ObjectId.is_valid(term): flt = {field.name: term} else: continue elif field.name.startswith("_"): # Don't process internal fields, such as _cls # which will be used in cases of inherited document classes continue else: flt = {'%s__%s' % (field if isinstance(field, string_types) else field.name, op): term} q = mongoengine.Q(**flt) if criteria is None: criteria = q else: criteria |= q return query.filter(criteria)
def edit_book(book_id): """ Checks if user is signed in and is admin, then render editbook.html """ if ObjectId.is_valid(book_id): the_book = mongo.db.books.find_one({"_id": ObjectId(book_id)}) if 'username' in session and session['username'] == 'admin': return render_template('editbook.html', book=the_book) return render_template('sorry.html') return render_template('nosuchbook.html')
def extract_creation_date(document, primary_key): if primary_key in document: objectId = document[primary_key] if ObjectId.is_valid(objectId): return ObjectId(objectId).generation_time return None
async def read_one(movie_id: str): collection = get_collection("movies") if ObjectId.is_valid(movie_id): found = await collection.find_one({"_id": ObjectId(movie_id)}) if found: return found # raise HTTPException(status_code=404, detail="Not found.") # It's OK return JSONResponse({"error": "NOT FOUND"}, status_code=404)
def toObjectId(value): """ if value is valid string convert it to ObjectId else leave unchanged """ if isinstance(value, str) and ObjectId.is_valid(value): return ObjectId(value) return value
def validate(cls, v): if not ObjectId.is_valid(v): raise ValueError('Invalid objectid') return ObjectId(v) # @classmethod # def __modify_schema__(cls, field_schema): # field_schema.update(type='string')
def get_menu(menu_id): #check if menu_id coming in from URL is a valid ObjectId format if (ObjectId.is_valid(menu_id)): menu = mongo.db.menus.find_one_or_404({'_id': ObjectId(menu_id)}) else: abort(404) return mongo_to_jsonResponse(menu)
def delete_book(book_id): """ Checks if user is signed in and is admin, then deletes a book """ if ObjectId.is_valid(book_id): if 'username' in session and session['username'] == 'admin': mongo.db.books.delete_one({'_id': ObjectId(book_id)}) return redirect(url_for('allbooks')) return render_template('sorry.html') return render_template('nosuchbook.html')
def delete_menu(menu_id): #check if menu_id coming in from URL is a valid ObjectId format if (ObjectId.is_valid(menu_id)): mongo.db.menus.find_one_or_404({'_id': ObjectId(menu_id)}) else: abort(404) mongo.db.menus.remove({'_id': ObjectId(menu_id)}) return jsonify({'delete': 'success'})
def get_contact(id): if not ObjectId.is_valid(id): return {"message": "Invalid ID"} contact = {"_id": ObjectId(id)} find = col.find_one(contact) if find is None: return {"error": "contact not found"} return {'_id': str(contact['_id']), 'name': find['name'], 'number': find['number'], 'email': find['email']}
def extract_creation_date(document, primary_key): if primary_key in document: objectId = document[primary_key] if ObjectId.is_valid(objectId): return ObjectId(objectId).generation_time return None
def get_place(placeId): if not ObjectId.is_valid(photoId): raise BadRequest('Invalid id value.') objectId = ObjectId(placeId) place = places_collection.find_one({'_id' : objectId}) place['_id'] = str(place['_id']) return json.dumps({'place' : place}, indent = 4, ensure_ascii = False)
def class_from_id(type_, _id): """ Return an instantiated class object. :param type_: The CRIPTs top-level object type. :type type_: str :param _id: The ObjectId to search for. :type _id: str :returns: class which inherits from :class:`cripts.core.cripts_mongoengine.CriptsBaseAttributes` """ #Quick fail if not _id or not type_: return None # doing this to avoid circular imports from cripts.comments.comment import Comment from cripts.core.cripts_mongoengine import Action from cripts.core.source_access import SourceAccess from cripts.core.user_role import UserRole from cripts.events.event import Event from cripts.usernames.username import UserName from cripts.targets.target import Target from cripts.hashes.hash import Hash from cripts.datasets.dataset import Dataset from cripts.email_addresses.email_address import EmailAddress # make sure it's a string _id = str(_id) # Use bson.ObjectId to make sure this is a valid ObjectId, otherwise # the queries below will raise a ValidationError exception. if not ObjectId.is_valid(_id.decode('utf8')): return None if type_ == 'Comment': return Comment.objects(id=_id).first() elif type_ == 'Event': return Event.objects(id=_id).first() elif type_ == 'Action': return Action.objects(id=_id).first() elif type_ == 'SourceAccess': return SourceAccess.objects(id=_id).first() elif type_ == 'UserRole': return UserRole.objects(id=_id).first() elif type_ == 'UserName': return UserName.objects(id=_id).first() elif type_ == 'Target': return Target.objects(id=_id).first() elif type_ == 'Hash': return Hash.objects(id=_id).first() elif type_ == 'Dataset': return Dataset.objects(id=_id).first() elif type_ == 'EmailAddress': return EmailAddress.objects(id=_id).first() else: return None
def mutate(self, root, fields): if ObjectId.is_valid(fields['bot_message']['recipient_id']) is True: fields['bot_message']['recipient_id'] = ObjectId( fields['bot_message']['recipient_id']) if ObjectId.is_valid(fields['bot_message']['sender']) is True: fields['bot_message']['sender'] = ObjectId( fields['bot_message']['recipient_id']) for message in fields['messages']: if ObjectId.is_valid(message['recipient_id']) is True: message['recipient_id'] = ObjectId(message['recipient_id']) if ObjectId.is_valid(message['sender']) is True: message['recipient_id'] = ObjectId(message['sender']) fields['user_id'] = ObjectId(get_jwt_identity()) fields['created_at'] = datetime.datetime.now() result = mongo.db.chatbot_feedbacks.insert_one(dict(fields)) if result.inserted_id is None: return CreateChatbotFeedback( created_feedback=None, response=ResponseMessage( text='Umpan balik pesan chatbot berhasil dikirim', status=True)) created_feedback = mongo.db.chatbot_feedbacks.find_one({ '_id': result.inserted_id, 'user_id': ObjectId(get_jwt_identity()) }) created_feedback['user'] = mongo.db.users.find_one( {'_id': ObjectId(get_jwt_identity())}) created_feedback['created_at'] = { 'date': created_feedback['created_at'].date(), 'time': created_feedback['created_at'].time() } return CreateChatbotFeedback( created_feedback=created_feedback, response=ResponseMessage( text='Umpan balik pesan chatbot berhasil dikirim', status=True))
def todo_update(id): content = request.get_json(force=True) content['modificationDate'] = int(time()) if ObjectId.is_valid(id): result = todos.update_one({'_id': ObjectId(id)}, {'$set': content}) if result.modified_count > 0: return jsonify({'result': 'Updated ' + id}) return not_found()
def __init__(self, oid=None): if not ObjectId.is_valid(oid): print("The user ID '%s' is not a valid Object ID." % (oid)) sys.exit(1) self._id = ObjectId(oid) self.User = users.User(_id=self._id) self.login = self.User.user['login'] print("\n Working with user \x1b[1;33;40m %s \x1b[0m [%s]" % (self.login, self._id))
def retrieve_job_activity(object_id): """Returns a single job post or none if not found""" activities = MongoConnection.get_activities_client() if not ObjectId.is_valid(object_id): return None activity = activities.find_one({"_id": ObjectId(object_id)}) if activity is not None: activity["_id"] = str(activity["_id"]) return activity
def get_tag(entry_id): if not ObjectId.is_valid(entry_id): return APIResponse.bad_request('invalid entry id') tag = DB().tag.find_one({'_id': ObjectId(entry_id)}) if not tag: return APIResponse.not_found() return APIResponse.ok({'entry': tag})
def get_module_version(version_id): if not ObjectId.is_valid(version_id): raise ModuleVersionInvalidId() module_version = instance.find_one( ModVersionsConst.COLLECTION_NAME, {ModVersionsConst.FIELD_ID: ObjectId(version_id)}) MongodbFactory.validate_module_version_params(module_version) return module_version
def get_by_id(user_id): u = None if ObjectId.is_valid(user_id): #chequea si un string OID es válido, tiene la notación de MongoDB u = db['user'].find_one({ "_id": ObjectId(user_id)}) if u is not None: user = User(u['name'], u['email'], u['is_admin']) user.password = u['password'] user.id = u['_id'] return user
async def remove_item(self, _id) -> Tuple[bool, str]: if not ObjectId.is_valid(_id): return False, 'invalid_id' _id = ObjectId(_id) result = await self.collection.delete_one({'_id': _id}) if result.deleted_count == 1: return True, 'removed' return False, 'failed'
def delete_poll(poll_id): user_id = ObjectId(get_jwt_identity()) if not ObjectId.is_valid(poll_id): return return_error("Invalid ID format!") db.polls.delete_one({"_id": ObjectId(poll_id), "_user_id": str(user_id)}) return return_json(""), 204
def add_event_user(db, event_id, user): try: if ObjectId.is_valid(event_id): db.Events.update_one({"_id": ObjectId(event_id)}, {"$push": { "users": user }}) except Exception as e: print(e)
def get_document_comments(self, document_id: str) -> Optional[List]: if not ObjectId.is_valid(document_id): return None comments = list(self.db.comments.find({"document_id": document_id})) for comment in comments: comment["_id"] = str(comment["_id"]) return comments
async def get(db: DBClient, ref: str): logging.info(">>> " + __name__ + ":" + get.__name__) collection = utils.get_collection(db, config.DOCTYPE_USER) if ObjectId.is_valid(ref): logging.info("objectid") return await utils.get(collection, ref) elif ("@" in ref) and ("." in ref): return await utils.get(collection, ref, "email") return await utils.get(collection, ref, "username")
def verifyAccessToken(access_token): if not ObjectId.is_valid(access_token): return 'Invalid access token', False token = tokens.find_one({'_id': ObjectId(access_token)}) if token is None: return 'Invalid access token', False return None, True
def delete(self, getid=None): ''' DELETE - /deletedocuments/<getid> ''' client_id = request.headers.get('x-client') id_valid = None resp_code = None # Checks if database is available or not if check_database() is not True: logger.debug('DB connection error') traceback.print_stack(limit=1) results = {'message': 'Server is not available'} resp_code = ResponseValues.FAILURE.value return results, resp_code #Checks if valid id provided if getid and ObjectId.is_valid(getid): id_valid = True else: logger.debug('Correct Id is not provided for delete operation') traceback.print_stack(limit=1) results = {'message': 'Server is not available'} resp_code = ResponseValues.FAILURE.value return results, resp_code if client_id is None: logger.debug('Client_id not found') traceback.print_stack(limit=1) results = {'message': 'Client_id not found'} resp_code = ResponseValues.FAILURE.value return results, resp_code if check_collection(client_id) is not None: collection_name = check_collection(client_id) else: logger.debug('No Collection of name ' + str(client_id) + ' is present') traceback.print_stack(limit=1) results = {'message': 'Server is not available'} resp_code = ResponseValues.FAILURE.value return results, resp_code if id_valid and collection_name.find({ "_id": ObjectId(getid) }).count() != 0: collection_name.remove({"_id": ObjectId(getid)}) logger.info('data deleted successfully for ' + getid) results = {'message': 'data deleted successfully for ' + getid} resp_code = ResponseValues.SUCCESS.value else: logger.info('No document present for ' + getid) traceback.print_stack(limit=1) results = {'message': 'Server is not available'} resp_code = ResponseValues.FAILURE.value return results, resp_code
async def read_by_project(id: str, limit: int = 50, skip: int = 0, db: DBClient = client): logging.info(f">>> {__name__}:{read_by_project.__name__}") if not ObjectId.is_valid(id): return utils.create_422_response("Invalid ObjectId") evidences = await crud.get_by_project(db, id, limit, skip) return utils.create_aliased_response( ManyGPQEvidencesResponse(response=evidences, count=len(evidences)))
def getUserCredentialsById(uid): if not ObjectId.is_valid(uid): return 'Invalid ID', False user = users.find_one({'_id': ObjectId(uid)}) if user is None: print("User with id " + uid + "was not found") return 'No user found', False return user, True
def removeJobs(self, jobID='all'): if jobID == 'all': rst = self.dbMgr.removeJobs() self.__writelnLog('Info: {0} job[s] removed'.format(rst)) else: if ObjectId.is_valid(jobID): rst = self.dbMgr.removeJobByID(jobID) self.__writelnLog('Info: {0} job removed'.format(rst)) else: self.__writelnLog('Error: invalid job ID {0}'.format(jobID))
def delete(self, request, *args, **kw): #deletes table db_id = request.data.get('db_id', None) table_id = request.data.get('table_id', None) access_token = request.META.get('HTTP_ACCESS_TOKEN', None) result = {} result[RESPONSE_STATUS] = RESPONSE_STATUS_ERROR if db_id and ObjectId.is_valid(db_id) and access_token: mainDB = getDatabase() token = mainDB.tokens.find_one({"token": access_token }) if mainDB else None if token and access_token_valid(token): if mainDB: result[RESPONSE_STATUS] = RESPONSE_STATUS_SUCCESS if table_id: if ObjectId.is_valid(table_id): result[ DELETED_TABLE_COUNT] = mainDB.tables.delete_one( { "_id": ObjectId(table_id), "author": token['author'], "database_id": ObjectId(db_id) }).deleted_count else: result[RESPONSE_STATUS] = RESPONSE_STATUS_ERROR result[ RESPONSE_STATUS_ERROR_MSG] = TABLE_ID_INVALID else: result[ DELETED_TABLE_COUNT] = mainDB.tables.delete_many({ "author": token['author'], "database_id": ObjectId(db_id) }).deleted_count else: result[RESPONSE_STATUS_ERROR_MSG] = MASTER_DB_UNINITIALIZED else: result[RESPONSE_STATUS_ERROR_MSG] = ACCESS_TOKEN_INVALID else: result[ RESPONSE_STATUS_ERROR_MSG] = TOKEN_MISSING if not access_token else DATABASE_ID_INVALID response = Response(result, status=status.HTTP_200_OK) return response
def get_user_event_details(oid): try: if ObjectId.is_valid(oid): host_data = audit_collection.find_one({"_id": ObjectId(oid)}) else: host_data = audit_collection.find_one({"_id": ast.literal_eval(oid)}) formatted = dumps(host_data, indent=2) return render_template('user_event_details_data.html', data=formatted, dtg=host_data['ts']) except OperationFailure as e: print(e.details)
def update_module_last_modify(id): if not ObjectId.is_valid(id): raise ModuleInvalidId() return instance.update_one(ModuleConst.COLLECTION_NAME, { ModuleConst.FIELD_ID: ObjectId(id) }, {'$set': { ModuleConst.FIELD_UPDATE_AT: datetime.datetime.utcnow() }}, upsert=False)