def mutate(self, info, **args): id_ = args.get('id') department = db_session.query(Department).get(id_) if department: db_session.delete(department) db_session.commit() return DeleteDepartment(status="OK")
def delete_user(username): user = User.query.filter_by(username=username).first() if user is None: abort(404) db_session.delete(user) db_session.commit() return make_response(jsonify({'mobilerp': 'deleted'}, 200))
def edit_profile(): """Updates a profile""" if g.user is None: abort(401) form = dict(name=g.user.name, email=g.user.email) if request.method == 'POST': if 'delete' in request.form: db_session.delete(g.user) db_session.commit() session['openid'] = None flash(u'Profile deleted') return redirect(url_for('index')) form['name'] = request.form['name'] form['email'] = request.form['email'] if not form['name']: flash(u'Error: you have to provide a name') elif '@' not in form['email']: flash(u'Error: you have to enter a valid email address') else: flash(u'Profile successfully created') g.user.name = form['name'] g.user.email = form['email'] db_session.commit() return redirect(url_for('edit_profile')) return render_template('edit_profile.html', form=form)
def user_delete(user_id): user = User.get(user_id) if user is None: abort(404) db_session.delete(user) db_session.commit() return jsonify({})
def mutate(root, info, orderId): order = db_session.query(OrderModel).filter(OrderModel.orderId == orderId).first() db_session.delete(order) db_session.commit() ok = True return DeleteOrder(ok=ok)
def mutate(root, info, productId): product = db_session.query(ProductModel).filter(ProductModel.productId == productId).first() db_session.delete(product) db_session.commit() ok = True return DeleteProduct(ok=ok)
def __remove_last_op__(self): total_ops = OperationsLogs.query.count() while (total_ops > self.log_limit): op = OperationsLogs.query.first() db_session.delete(op) db_session.commit() total_ops -= 1
def delete_task(task_id, member_id): ''' INPUT Triggered via a close button element, handed the task_id implicitly from the page request. Assumes there will be a member_id and group_id in the request. REQUIREMENT Can only be used before a task has been delivered. OUTPUT Removes a Task entry from the database, erasing it from the Tasks of each Member. ''' # Grab the Task we need. task = Task.query.get(task_id) member = Member.query.get(member_id) # Sanity check -- does this Member have delete rights -- i.e. are they an approving member? if task.is_approving(member): # Yup! Delete it and save our work. db_session.delete(task) db_session.commit() else: # No! Scoundrels, throw up an Exception. raise Exception("This Member is trying to delete a Task they aren't approving!")
def toggle_comment_like(request, sse, comment_id): comment = db_session.query(EventComments).filter_by(id=comment_id).first() if not comment: return jsonify(error=True, message='comment not found') like = db_session.query(CommentLikes) \ .filter_by(comment_id = comment_id) \ .filter_by(owner_id = user_session['account_id']) \ .first() if like: db_session.delete(like) check_notification = db_session.query(Notifications) \ .filter(Notifications.action == ACTION_TYPES['COMMENT_LIKE']) \ .filter(Notifications.target_type == TARGET_TYPES['COMMENT']) \ .filter(Notifications.target_id == like.comment_id) \ .filter(Notifications.from_id == user_session['account_id']) \ .filter(Notifications.account_id == like.comment_rel.owner_id) \ .first() if check_notification: db_session.delete(check_notification) db_session.commit() return jsonify(message='unliked', liked=False) else: like = CommentLikes(comment_id=comment_id, owner_id=user_session['account_id']) db_session.add(like) db_session.commit() if like.comment_rel.owner_id != user_session['account_id']: you = db_session.query(Accounts).filter_by( id=user_session['account_id']).one() message = you.username + ' liked your comment: ' + like.comment_rel.text new_notification = Notifications( action=ACTION_TYPES['COMMENT_LIKE'], target_type=TARGET_TYPES['COMMENT'], target_id=like.comment_id, from_id=user_session['account_id'], account_id=like.comment_rel.owner_id, message=message, link='/event/' + str(like.comment_rel.event_rel.id)) db_session.add(new_notification) db_session.commit() sse.publish( { "message": message, "for_id": like.comment_rel.owner_id }, type='action') return jsonify(message='liked', liked=True)
def handleRemoveGeopointGroup(self): """ 删除指定的整个地理坐标集合 需要校验地理坐标集合是否属于操作者本人 :return: """ gid, pwd = self.postParams("gid", "pwd") if self.checkParamsAvailable(gid, pwd): if self.userIdentification(pwd): current_user = UserIdentify() geo_group_info = db_session.query(GeoPointGroup).filter(GeoPointGroup.id==gid).first() if geo_group_info is not None: if (geo_group_info.u_id == current_user.uid): try: # 删除集合下的所有观察子节点 db_session.query(GeoPointUnit).filter(GeoPointUnit.group_id==gid).delete() db_session.delete(geo_group_info) db_session.commit() self.changeResponse2Success() except Exception as e: self.setFailureReason(str(e), redirect_url=url_for(".ViewGeoGroup", gid=gid)) else: self.setFailureReason("该地理坐标点位集合不属于您,无法执行删除操作!", redirect_url=url_for(".ViewGeoGroup", gid=gid)) else: self.setFailureReason("指定的地理坐标点位集合不存在!", redirect_url=url_for(".ViewGeoGroup", gid=gid)) else: self.setFailureReason("对不起,您不具备执行当前操作的权限!", redirect_url=url_for(".ViewGeoGroup", gid=gid))
def mutate(self, info, deleteId): deleteUser = db_session.query(UserModel).filter( UserModel.id == deleteId).one() db_session.delete(deleteUser) db_session.commit() return DeleteUser(deleteId=deleteId)
def delete(self, post_id): """Removes the post identified by post_id.""" post = db_session.query(Post).get(post_id) if not post: abort(404, message='Post does not exists') db_session.delete(post) db_session.commit() return {'message':'succesfuly deleted the post.'}
def mutate(self, info, id): query = Publicholiday.get_query(info) holiday_id = from_global_id(id)[1] publicHoliday = query.filter( PublicholidayModel.id == holiday_id).first() db_session.delete(publicHoliday) db_session.commit() ok = True return DeletePublicholiday(publicHoliday=publicHoliday, ok=ok)
def del_one_user(user_id): """ removes a user by their id """ try: user = db_session.query(User).filter(User.id == user_id).one() db_session.delete(user) db_session.commit() return jsonify({}) except: abort(404)
def delete_all_users(): """ Deletes all user records """ try: users = all() for user in users.values(): db_session.delete(user) db_session.commit() return jsonify({}), 200 except Exception: abort(404)
def delete_all_users(): """ Deletes all user records """ all_obj = all() try: for k, v in all_obj.items(): user = all_obj.get(k) db_session.delete(user) db_session.commit() except: raise Exception("couldn't delete 1 or more user records, rolling back") return jsonify({}), 200
def delete_user(user_id): """ retrieves an user and deletes it """ user = db_session.query(User).get(user_id) if user is None: return abort(404) else: db_session.delete(user) db_session.commit() return jsonify()
def delete_user(user_id): """ Deletes a single user record """ try: all_obj = all() _id = "User.{}".format(user_id) user = all_obj.get(_id) db_session.delete(user) db_session.commit() return jsonify({}), 200 except Exception: abort(404)
def folders_delete(folder_id, user): if not user.admin: return error_response("not_admin", "You must be an administrator to " "delete a folder") f = Folder.query.get(folder_id) if not f: return error_response("item_not_found", "Folder not found") db_session.delete(f) db_session.commit() return jsonify(success=True)
def deleteDealer(): if not request.json or (not "id" in request.json): abort(400) result = db_session.query(Dealer).filter( DealerModel.id == request.json['id']).first() if (result == None): abort(404) id = result.id name = result.name country = result.country db_session.delete(result) db_session.commit() return jsonify({'id': id, 'name': name, 'country': country})
def delete_user(user_id): """route /users/<user_id> returns - {} :param user_id: user id of user to be deleted """ user = User.get(user_id) if user is None: return abort(404) else: db_session.delete(user) db_session.commit() return jsonify()
def accounts_delete(account_id, user): a = Account.query.get(account_id) if not a: return error_response("item_not_found", "Account not found") if not a.folder.user_can_write(user): return error_response("insufficient_permissions", "You do not have " "write permission for this folder") db_session.delete(a) db_session.commit() return jsonify(success=True)
def destroy_session(self, request=None): """ removes a session """ try: sess_id = self.session_cookie(request) if sess_id is None: return False sess = db_session.query(UserSession).filter( UserSession.session_id == sess_id).one() db_session.delete(sess) db_session.commit() return True except: return False
def remove_member(member_id): ''' INPUT A Member ID for the member to be removed. OUTPUT Removes the specified Member's row from the database, removing them from all Roles they were assigned to. If a Task was only assigned to them, it is removed as well. ''' member = Member.query.get(member_id) db_session.delete(member) db_session.commit() return True
async def del_filament(self, ctx: Context, filament_name: clean_content): filament = (db_session.query(FilamentType).filter( FilamentType.name.like(filament_name)).first()) if not filament: await ctx.send( f'Couldn\'t find a filament that matches the name "{filament_name}"' ) return db_session.delete(filament) db_session.commit() await ctx.send(f'Removed "{filament_name}" from the filament list!')
def delete_group(group_code_name): ''' INPUT Takes the ID of the group and the User_ID of the person who submitted the request for deletion. OUTPUT Deletes the Group from the database, including all of its Members, Roles, and Tasks. If the User_ID does not match up with that of the administrator, the request does not succeed. ''' group = Group.query.filter_by(code_name=group_code_name) db_session.delete(group) db_session.commit() return True
def destroy_session(self, request=None): """Overloading :param request: Default value = None) """ if request: session_id = self.session_cookie(request) if session_id: if super(SessionDBAuth, self).destroy_session(request): for user_session in db_session.query(UserSession).filter( UserSession.session_id == session_id): db_session.delete(user_session) db_session.commit() return True return False
def mutate(self, info, merge_to_id, duplicate_id): if merge_to_id == duplicate_id: return MergeSongMutation(ok=False) merge_to_artist = ArtistModel.query.get(merge_to_id) duplicate_artist = ArtistModel.query.get(duplicate_id) merge_to_artist.alt_names.append( ArtistNameModel(name=duplicate_artist.name)) for alt_name in duplicate_artist.alt_names: alt_name.artist = merge_to_artist for song in duplicate_artist.songs: song.artists.append(merge_to_artist) db_session.delete(duplicate_artist) db_session.commit() return MergeArtistMutation(ok=True)
def handleDeletePropertyForProject(self): """ 删除指定的研究项目属性 :return: """ _id, = self.postParams("id") if self.checkParamsAvailable(_id): try: _del_property = db_session.query(ProjectProperty).filter(ProjectProperty.id==_id).first() if _del_property is not None: db_session.query(ProjectItem.proj_id==_del_property.p_id).filter(ProjectItem.label==_del_property.label).delete() db_session.delete(_del_property) db_session.commit() self.changeResponse2Success() except Exception as e: db_session.rollback() self.setFailureReason(str(e))
def delete_blog(): title = request.form['title'] print title delete_blog_post = db_session.query(Blog_Post).first() show = db_session.relationship('Show', backref=db.backref('episodes', cascade="all, delete-orphan"), lazy='joined') print delete_blog_post db_session.delete(delete_comments) db_session.delete(delete_blog_post) try: print "succsess" db_session.commit() except Exception as e: print "error" db_session.rollback() db_session.flush() return redirect(url_for('routes.add_blog'))
def delete_alias(self, json): """別名削除""" args = loads(json) print args user = self._whoami(args["caller"]) if user is None: return dumps((False,)) try: alias = db_session.query(UserAlias ).filter(UserAlias.name==args["alias"] ).one() except: return dumps((False,)) if (alias.user.id != user.id) and (not user.admin): return dumps((False,)) db_session.delete(alias) db_session.commit() return dumps((True,))
def delete_event(request, event_id): ''' INPUT Member object in the request to validate Permissions. Other than that, the event_id is enough. RESULT If all goes well, event is deleted and returns True. Otherwise, an Exception. ''' # If they want it deleted... if request.form['delete'] == True: # Grab the specified Event event = Event.query.get(event_id) # Delete it and save our work. db_session.delete(event) db_session.commit()
def handleDeleteGeoPointUnit(self): """ 从坐标节点集中删除一个坐标节点 :return: """ gid, geopt = self.getParams("gid", "geopt") if self.checkParamsAvailable(gid, geopt): geo_unit = db_session.query(GeoPointUnit).filter(GeoPointUnit.group_id==gid).\ filter(GeoPointUnit.id==geopt).first() if geo_unit is not None: try: db_session.delete(geo_unit) db_session.commit() self.changeResponse2Success() except Exception as e: db_session.rollback() self.setFailureReason(str(e)) else: self.setFailureReason("地理兴趣点坐标未找到")
def submit_password_reset_code(request): data = json.loads(request.data) if "code" not in data: return jsonify(error = True, message = "Code field is required") code = cgi.escape(data['code']) if not code: return jsonify(error = True, message = "Code field cannot be blank") reset_request = db_session.query(ResetPasswordRequests).filter_by(unique_value = code).first() if not reset_request: return jsonify(error = True, message = "Invalid code") you = db_session.query(Users).filter_by(email = reset_request.user_email).first() new_password = chamber.uniqueValue() hash = bcrypt.hashpw(new_password, bcrypt.gensalt()).encode('utf8') print("reset - ", new_password, hash, you) you.password = hash db_session.add(you) db_session.delete(reset_request) db_session.commit() checkPassword = bcrypt.hashpw(new_password, you.password.encode('utf8')) if checkPassword != you.password: print("new password test failed...") return jsonify(error = True, message = "Server error: could not reset password...") else: print("new password test successful!") body = render_template("email/PasswordResetSuccess.html", data = { "user": you.serialize_small, "password": new_password, "link": request.host + "/signin" } ) mail_sent = chamber.send_email(you.email, "Password Reset Successful!", "text/html", body) return jsonify(message = "New password reset successful! Check your email.")
def get_user(user_id): '''get_user() - get user info, delete user and udpate user info by id''' user = User.get(user_id) if user is None: abort(404) if request.method == 'GET': return jsonify(user.to_dict()) if request.method == 'DELETE': db_session.delete(user) db_session.commit() return jsonify({}) if request.method == 'PUT': if not request.json: return make_response(jsonify(error="Wrong format"), 400) if request.json.get('first_name'): user.first_name = request.json.get('first_name') if request.json.get('last_name'): user.last_name = request.json.get('last_name') db_session.commit() return jsonify(user.to_dict())
async def del_filament(self, ctx: Context, filament_name: clean_content): filament = (db_session.query(FilamentType).filter( FilamentType.name.like(filament_name)).first()) if not filament: await ctx.send( f'Couldn\'t find a filament that matches the name "{filament_name}"' ) return db_session.delete(filament) try: db_session.commit() await ctx.send(f'Removed "{filament_name}" from the filament list!' ) except (ScalarListException, SQLAlchemyError): db_session.rollback() await ctx.send( f'Could not remove "{filament_name}" due to an internal error.' )
def mutate(self, info, merge_to_id, duplicate_id): if merge_to_id == duplicate_id: return MergeSongMutation(ok=False) merge_to_song = SongModel.query.get(merge_to_id) duplicate_song = SongModel.query.get(duplicate_id) merge_to_song.alt_names.append(SongNameModel(name=duplicate_song.name)) # TODO: if duplicate song has an identical alt name, the merged song will have 2 alt names that are identical, we need to filter alt names first for alt_name in duplicate_song.alt_names: alt_name.song = merge_to_song for artist in duplicate_song.artists: merge_to_song.artists.append(artist) for tag in duplicate_song.tags: merge_to_song.tags.append(tag) for link in duplicate_song.links: link.song = merge_to_song db_session.delete(duplicate_song) db_session.commit() return MergeSongMutation(ok=True)
def process_edit(pagename, form, ip_addr): url_name = form['url_name'] content = form['content'].strip() is_public = form.get('is_public', False) now = datetime.now() article = Article.query.filter(Article.name == pagename).first() is_new_page = article is None if is_new_page: article = Article(name=pagename, time_create=now) is_updated = is_article_updated(article, form) if not (is_new_page or is_updated): return redirect(url_for('read', pagename=pagename)) article.url_name = url_name article.content = content article.ip_address = ip_addr article.html, links = parse_content(pagename, content) article.time_edit = now article.links = '' article.is_public = 1 if is_public else 0 all_names = Article.query.with_entities(Article.name).all() all_names = [x.name for x in all_names] existing_links = Link.query.filter_by(from_name=pagename).all() for l in existing_links: db_session.delete(l) db_session.commit() added_names = set() for l in links: if l in all_names and l not in added_names: new_link = Link(from_name=pagename, to_name=l) added_names.add(l) db_session.add(new_link) add_history(article, is_new_page) return redirect(url_for('read', pagename=pagename))
def delete_status(id): dele = OrderStatus.get_status(id) db_session.delete(dele) db_session.commit()
def deleteOrder(orderId): removeOrder = Order.get_order(orderId) db_session.delete(removeOrder) db_session.commit()
def deleteRecord(regionId): remove_region = db_session.query(RegionDao).get(regionId) db_session.delete(remove_region) db_session.commit()
def deleteActionPointToRole(apToRoleId): remove_apToRole = db_session.query(ActionPointToRoleDao).get(apToRoleId) db_session.delete(remove_apToRole) db_session.commit()
def deleteRecord(roleId): remove_role = db_session.query(RoleDao).get(roleId) db_session.delete(remove_role) db_session.commit()
def folders_set_permissions(user, folder_id): if not user.admin: return error_response("not_admin", "You must be an administrator to " "edit the permissions on a folder") schema = { "type": "object", "properties": { "permissions": { "type": "array", "items": { "type": "object", "properties": { "user_id": {"type": "integer"}, "read": {"type": "boolean"}, "write": {"type": "boolean"} }, "required": ["user_id", "read", "write"] } } }, "required": ["permissions"] } error = validate_schema(request.json, schema) if error: return error if not Folder.query.filter(Folder.id==folder_id).count(): return error_response("item_not_found", "Folder not found") for permission in request.json.get("permissions"): user_id = permission.get("user_id") u = User.query.get(user_id) if not u: return error_response("item_not_found", "User with ID {} not found" "".format(user_id)) if u.admin: return error_response("input_validation_fail", "Cannot set " "permissions for an administrator, administrators already have " "full access to all folders") ps = Permission.query.filter(Permission.user_id==user_id).filter( Permission.folder_id==folder_id).all() p = ps[0] if ps else Permission() # If no read or write, do not add permission and delete if exists if not(permission.get("read") or permission.get("write")): if ps: db_session.delete(p) continue if permission.get("write") and not permission.get("read"): return error_response("input_validation_fail", "Users must be able " "to read a folder if they are to write to it") p.user_id = user_id p.folder_id = folder_id p.read = permission.get("read") p.write = permission.get("write") if not ps: db_session.add(p) db_session.commit() return jsonify(success=True)
def deleteRecord(userId): remove_user = UserDao.getUserByID(userId) db_session.delete(remove_user) db_session.commit()
def delete_delivery(id): del_delivery = DeliveryType.get_delivery(id) db_session.delete(del_delivery) db_session.commit()
def delete_order_product(order_id, product_id, dimension_id): del_order_product = OrderProduct.get_order_product(order_id, product_id, dimension_id) if del_order_product: db_session.delete(del_order_product) db_session.commit()
def delete_book(book_id): book_user = BookForUser.query.filter_by(user_id=g.user.id, book_id=book_id).first() db_session.delete(book_user) db_session.commit() return '' # ok