def book_rm(id): book = db_session.query(Book).get(id) if book: db_session.delete(book) db_session.commit() flash('Deleted.', 'warning') return redirect(url_for('index'))
def delete_catalog(catalog_name): """Delete a selected catalog""" catalog = Catalog.query.filter(Catalog.name == catalog_name).first() # validate the catalog belongs to current user if not catalog.user_id == session.get('user_id'): flash("you can't delete other user's catalog") print("user id:{} trying to delete other user's catalog".format( str(session.get('user_id')))) return redirect(url_for('console')) if request.method == 'POST': # in case someone get around with default GET method if len(catalog.items) > 0: flash('Can not delete catalog with item in it') return redirect('/{}/items'.format(catalog.name)) try: db_session.delete(catalog) db_session.commit() except: flash('Something went wrong, can not delete this catalog') return redirect(url_for('console')) flash("catalog '{}' had been deleted".format(catalog_name)) print("catalog '{}' had been deleted".format(catalog_name)) return redirect(url_for('console')) else: num_items = len(catalog.items) return render_template('delete_catalog.html', catalog_name=catalog_name, num_items=num_items)
def removeMember(): decoded_token = decode_auth_token(request.json["token"]) if decoded_token["status"] == "success": userID = request.json["id"] space = request.json["space"] # Find the user from tables import User user = User.query.filter(User.id == userID).first() # Remove the space from his list of spaces listSpaces = stringToList(user.stringSpaces) newList = [] for sp in listSpaces: if sp != space: newList.append(sp) user.stringSpaces = listToString(newList) # Delete all the items owned by this user in this space from tables import Item listItems = Item.query.filter( and_(Item.space == (int)(space), Item.userID == (int)(userID))).all() for item in listItems: db_session.delete(item) db_session.commit() return jsonify({'status': 'success'}), 201 else: # Either the token is invalid either it is expired return jsonify({'status': 'fail', 'message': decoded_token["message"]})
def remove_by_gamewith(wiki_id): obj = Umamusume.query.filter(Umamusume.gamewith_wiki_id == wiki_id).first() if not obj: obj = SupportCard.query.filter( SupportCard.gamewith_wiki_id == wiki_id).first() db_session.delete(obj) db_session.commit()
def problems_del(problem_id): """ Deletes a problem Params: problem_id (int): the problem to delete Returns: a redirect to the problem view page """ problem = model.Problem.query.filter_by(id=int(problem_id)).scalar() if problem is None: error = "Failed to delete problem \'{}\' as it doesn't exist.".format( problem.slug) current_app.logger.info(error) flash(error, "danger") return redirect(url_for("problems.problems_view")) try: db_session.delete(problem) db_session.commit() flash("Deleted problem \'{}\'".format(problem.slug), "warning") except IntegrityError: db_session.rollback() error = "Failed to delete problem \'{}\' as it's referenced in another DB element".format( problem.slug) current_app.logger.info(error) flash(error, "danger") return redirect(url_for("problems.problems_view"))
def delete_book(): if not check_login(): flash('Only authorised user can delete book. Please, login.', 'error') return redirect(url_for('login')) author = '' form = DeleteBook(request.form) if request.method == 'POST' and form.validate(): book_name = request.form['book_name'] book = BookNames.query.filter_by(book_name=book_name).first() if book: # Delete book dependency in Bookcase table. id_book_author = Bookcase.query.filter_by(book_id=book.id).all() for ids in id_book_author: db_session.delete(ids) db_session.commit() # Delete book in BookNames table. db_session.delete(book) db_session.commit() flash('Book "%s" successful delete.' % book_name) return redirect(url_for('books')) else: flash('No such book %s.' % book_name) variables = {'form': form} return render_template('delete_book.html', **variables)
def test_rejudging(self): """Tests rejudging endpoint""" # A version run is being added on db startup for run in model.Run.query.all(): db_session.delete(run) db_session.commit() setup_contest() self.login("admin", "pass") test_run = model.Run.query.first() self._judge_writ() self.assertIsNotNone(test_run.started_execing_time) self.assertIsNotNone(test_run.finished_execing_time) self.assertIsNotNone(test_run.run_output) rv = self.app.get( "/admin/runs/{}/rejudge".format(test_run.id), follow_redirects=True ) self.assertEqual(rv.status_code, 200) self.assertIsNone(test_run.started_execing_time) self.assertIsNone(test_run.finished_execing_time) self.assertIsNone(test_run.run_output)
def process_client_file(hostname, hash): f = request.files['file'] f.save(os.path.join(UPLOADED_PATH, secure_filename(f.filename))) command_entry = Commands.query.filter(Commands.hash == hash) if command_entry.first() is not None: #command_entry.status = "done" db_session.delete(command_entry.first()) fin = open(UPLOADED_PATH + "/" + f.filename, 'rb') files = {'file': fin} r = requests.post( "http://sandbox.etp-research.info:8090/tasks/create/submit", files=files) print r task_ids = r.json()["task_ids"] print task_ids[0] #command_entry.result = "http://sandbox.etp-research.info:8000/analysis/"+task_ids[0]+"/summary" a = Analysis() a.hash = hash a.filepath = f.filename a.system = "cuckoo" a.status = "done" a.link = "http://sandbox.etp-research.info:8000/analysis/" + str( task_ids[0]) + "/summary" db_session.add(a) db_session.commit() return 'file uploaded successfully'
def add_key(cube, ex_id, key, secret, passphrase): app.logger.debug('[%s] Adding keys' % (cube)) # Add initial transactions to database if add_balances(ex_id, key, secret, passphrase, cube): try: # Encrypt keys and add connection conn = Connection( user_id=cube.user_id, cube_id=cube.id, exchange_id=ex_id, key=e(key), secret=e(secret), passphrase=e(passphrase) ) conn.save_to_db() app.logger.info('[%s] Added API key for Ex_ID: %s' % (cube, ex_id)) message = 'API keys added successfully. Exchange connection is live!' cube.log_user_action("save_api_keys") cube.update_charts = 1 cube.save_to_db() return message except Exception as error: app.logger.debug('[%s] Trouble adding API key for Ex_ID: %s' % (cube, ex_id)) app.logger.debug(error) remove_balances(ex_id, cube) db_session.delete(cube) db_session.commit() raise else: remove_balances(ex_id, cube) db_session.delete(cube) db_session.commit() message = 'There was a problem adding your API keys.' return message
def deleteAllCameraInfo(): logs = CameraInfo.query.all() print("[master][deleteAllCameraInfo] Deleting All CameraInfo") for l in logs: db_session.delete(l) db_session.commit() return "All records of camera info deleted succesfully"
def deleteAllIpConfig(): print("[master][deleteAllIpConfig] Deleting All IpConfig") logs = IpConfig.query.all() for l in logs: db_session.delete(l) db_session.commit() return "All records of ip config deleted succesfully"
def delete_entry(entry_id): if not session.get('logged_in'): abort(401) to_del = Entry.query.get(entry_id) db_session.delete(to_del) db_session.commit() return redirect(url_for('show_entries'))
def deleteDoctor(): post = request.get_json() doctorToDelete=Doctor.query.get(post['doctorId']) db_session.delete(doctorToDelete) db_session.commit() response = {'returnCode': "SUCCESS", 'data':{}, 'errorCode':None} return jsonify(response)
def deleteClinic(): post = request.get_json() clinicToDelete= db_session.query(Clinic).get(post['id']) db_session.delete(clinicToDelete) db_session.commit() response = {'returnCode': "SUCCESS", 'data':{}, 'errorCode':None} return jsonify(response)
def author_rm(id): author = db_session.query(Author).get(id) if author: db_session.delete(author) db_session.commit() flash('Deleted.', 'warning') return redirect(url_for('index'))
def deleteMails(): result = dict( type=ProtocolTypes.DeleteMails, result=ResultCodes.Success ) if request.form['data']: got_data = json.loads(request.form['data']) from_keys = ['session_id', 'mail_indexes'] if checkContainKeys(from_keys, got_data): result['result'], got_user = checkSessionId(got_data['session_id']) if got_user: if len(got_data['mail_indexes']) > 0: got_mails = Mail.query.filter( Mail.id.in_(got_data['mail_indexes'])).all() if got_mails: for got_mail in got_mails: db_session.delete(got_mail) result['result'] = commitData() else: result['result'] = ResultCodes.InputParamError else: result['result'] = ResultCodes.InputParamError else: result['result'] = ResultCodes.AccessError return str(json.dumps(result))
def toggle_favorite(): """Adds or removes liked photos to or from the database.""" request_data = request.json user_id = request_data["user"] photo_url = request_data["photo"]["photoUrl"] photo = LikedPhoto.query.filter(LikedPhoto.photo_url == photo_url and LikedPhoto.user_id == user_id).first() if photo is None: lp = LikedPhoto( title = request_data["photo"]["title"], author = request_data["photo"]["author"], photo_url = request_data["photo"]["photoUrl"], link = request_data["photo"]["link"], tags = request_data["photo"]["tags"], user_id = user_id ) db_session.add(lp) db_session.commit() response = { "status": True, "action": "liked", "id": lp.id } else: db_session.delete(photo) db_session.commit() response = { "status": True, "action": "unliked" } return jsonify(response)
def delete_by_id(the_class, explanation, user_id): user_id = str(user_id) result = db_session.query(the_class).get(str(user_id)) if result: db_session.delete(result) else: raise ModelException(explanation + " " + str(user_id), 404)
def delete_pic(): #pic_id= request.args.get('pic_id', 0, type=str) pic_id=4 userid = 1 error=None error = checklogin() #删除照片 if (db_session.query(Picture).filter(Picture.id==pic_id).first()): this_pic = db_session.query(Picture).filter(Picture.id==pic_id).first() if this_pic.user_id == session['userid']: db_session.delete(this_pic) db_session.commit() else: session['error'] = "对不起,您没有该权限" else: session['error'] = "该照片不存在" if 'error' in session: result = session['error'] session.pop('error',None) else: error = '' return jsonify(error=error)
def parseImage(self, response): idads = response.meta['idads'] craglink = response.url img = Image.query.filter(Image.craglink == craglink).first() if img: db_session.delete(img) db_session.commit() extension = craglink.split('.')[-1] filename = craglink.split('/')[-1] if extension == "jpg": mime = "image/jpeg" else: mime = "image/" + extension image = response.body img = Image(extension = extension, mime = mime, filename = filename, craglink = craglink, idads = idads, image = image) db_session.add(img) try: db_session.commit() except: db_session.rollback() raise Exception("DB commit is not OK")
def deleteSpecialization(): post = request.get_json() specializationToDelete=db_session.query(Specialization).get(post['specId']) db_session.delete(specializationToDelete) db_session.commit() response = {'returnCode': "SUCCESS", 'data':{}, 'errorCode':None} return jsonify(response)
def book(bID): form = UpdateBookForm(request.form) authors = db_session.query(Author).all() form.authors.choices = [(i, authors[i - 1]) for i in xrange(1, len(authors) + 1)] selected_book = Book.query.filter(Book.id == bID).one() if request.method == 'GET': authors = selected_book.authors return render_template("book.html", authors=authors, \ book=selected_book, form=form) elif request.method == 'POST' and form.validate(): selected_book.title = form.new_title.data authors = request.form.getlist('authors') authors = Author.query.filter(Author.id.in_(authors)).all() for author in authors: if author in selected_book.authors: selected_book.authors.remove(author) else: selected_book.authors.append(author) db_session.commit() return redirect(url_for("book", bID=bID)) elif request.method == 'DELETE': flash('{book} is deleted'.format(book=selected_book.title)) db_session.delete(selected_book) db_session.commit() return url_for('index')
def delete_payment_by_transaction(transaction): try: record = db_session.query(Payment).filter(Payment.transaction == transaction).one() db_session.delete(record) db_session.commit() except: raise ValueError
def delCode(pn): """ Deletes a record from first or second pass codings. """ if False: pass elif pn == '1': a = db_session.query(CodeFirstPass).filter_by( article_id = request.args.get('article'), variable = request.args.get('variable'), value = request.args.get('value'), coder_id = current_user.id ).all() elif pn == '2': a = db_session.query(CodeSecondPass).filter_by( article_id = request.args.get('article'), variable = request.args.get('variable'), value = request.args.get('value'), event_id = request.args.get('event'), coder_id = current_user.id ).all() else: return make_response("Invalid model", 404) if len(a) > 0: for o in a: db_session.delete(o) db_session.commit() return jsonify(result={"status": 200}) else: return make_response("", 404)
def author(aID): form = UpdateAuthorForm(request.form) selected_author = Author.query.filter(Author.id == aID).one() books = Book.query.all() form.books.choices = [(i, books[i - 1]) for i in xrange(1, len(books) + 1)] if request.method == 'GET': books = selected_author.books return render_template("author.html", books=books,\ author=selected_author, form=form) elif request.method == 'POST' and form.validate(): selected_author.name = form.new_name.data books = request.form.getlist('books') books = Book.query.filter(Book.id.in_(books)).all() for book in books: if book in selected_author.books: selected_author.books.remove(book) else: selected_author.books.append(book) db_session.commit() return redirect(url_for("author", aID=aID)) elif request.method == 'DELETE': flash('{author} is deleted'.format(author=selected_author.name)) db_session.delete(selected_author) db_session.commit() return url_for('index')
def delete_lot(lot_id): lot = ParkingLot.query.get(lot_id) if not lot: return jsonify(dict(status='Failed')) db_session.delete(lot) db_session.commit() return jsonify(dict(status='Success'))
def deleteByPathologyId(cls,pathologyId): if pathologyId: pathologyPostions = session.query(PathologyPostion).filter(PathologyPostion.pathologyId == pathologyId).all() for position in pathologyPostions: session.delete(position) session.commit() session.flush()
def deleteRecipe(recipe_id): """RESTful method for deleting a recipe""" # Check if the token is correct to prevent CSRF if request.headers.get('italian-recipes-token') != login_session['state']: resp = jsonify(error=['You are not allowed to make such request.']) resp.status_code = 401 return resp # Check if user is logged in if 'username' not in login_session: resp = jsonify(error=['You are not allowed to do this']) resp.status_code = 401 return resp recipe = db_session.query(Recipe).filter( Recipe.id == recipe_id).one() # Check if current user is the recipe's owner if recipe.user_id != login_session['user_id']: resp = jsonify(error=['You are not authorized to do this!']) resp.status_code = 403 return resp # Delete the recipe's picture from the file system if(recipe.image_url is not None): removeImage(recipe.image_url) db_session.delete(recipe) db_session.commit() return jsonify(id=recipe.id)
def deleteSlide(): slide_id = request.form['id'] s = Slide.query.get(slide_id) db_session.delete(s) db_session.commit() status = True categories = getCategories() return render_template('admin.html', categories = categories, status = status, action='deleted')
def remove_video(video_id): video = Playlist.query.get(video_id) if video is None: raise ExistenceError("Video does not exist.") db_session.delete(video) db_session.commit()
def user_delete(): form = UserDeleteForm(request.form) if form.validate(): user = User.query.get(form.key.data) db_session.delete(user) db_session.commit() return jsonify({'message': 'deleted'}) return jsonify({'message': 'failed'})
def task_delete(): form = TaskFormDelete(request.form) if form.validate(): task = Task.query.get(form.key.data) db_session.delete(task) db_session.commit() return jsonify({'message': 'deleted'}) return jsonify({'message': 'failed'})
def delete_entry(entry_id): if not session.get('logged_in'): abort(401) entry = Entry.query.filter(Entry.id == entry_id).first() db_session.delete(entry) db_session.commit() flash(u'The entry was successfully deleted') return redirect(url_for('show_entries'))
def remove(self, _id): if _id is not None: obj = Database.query.filter_by(id=_id).first() db_session.delete(obj) db_session.commit() flash("Database connection deleted.", "alert-block") return redirect('/admin/databases')
def unregister(username): u = User.query.filter(User.uid == username).first() if u: os.unlink(os.path.join(app.config['UPLOAD_FOLDER'], u.mp3)) db_session.delete(u) db_session.commit() return "unregistered %s" % username return "%s doesn't exist." % username
def delete_planning(uuid): try: planning = _get_planning(uuid, g.user_id) db_session.delete(planning) db_session.commit() except CAPException as e: return e.res return jsonify({}), 204
def delete(instance=None,obj_id=None): if instance == 'author': obj = Author.query.filter_by(id=obj_id).first() if instance == 'book': obj = Book.query.filter_by(id=obj_id).first() db_session.delete(obj) db_session.commit() return redirect('/'+instance+'s')
def add_user_annotation(tablemd, loctype, colname): tablemd.tablename for anno in tablemd.annotations: if anno.loctype == loctype: db_session.delete(anno) db_session.add(Annotation(colname, loctype, 'parse_default', tablemd, user_set=True)) db_session.commit()
def delete_meta_from_id(meta_id): """Empty map means that no data was deleted""" result = db_session.query(MetaEntry).get(meta_id) if result: db_session.delete(result) return {} else: raise ModelException("Unknown meta_id" + meta_id, 404)