def on_delete(self, req, resp, id): try: user = req.context['user'] if (not user.is_logged_in()) or (not user.is_admin()): resp.status = falcon.HTTP_400 return year = session.query(model.Year).get(id) if year is None: resp.status = falcon.HTTP_404 return # Odstranit lze jen neprazdny rocnik waves_cnt = session.query(model.Wave).filter(model.Wave.year == year.id).count() if waves_cnt > 0: resp.status = falcon.HTTP_403 return session.delete(year) session.commit() req.context['result'] = {} except SQLAlchemyError: session.rollback() raise finally: session.close()
def on_delete(self, req, resp, id): try: user = req.context['user'] if (not user.is_logged_in()) or (not user.is_admin()): resp.status = falcon.HTTP_400 return year = session.query(model.Year).get(id) if year is None: resp.status = falcon.HTTP_404 return # Odstranit lze jen neprazdny rocnik waves_cnt = session.query(model.Wave).\ filter(model.Wave.year == year.id).\ count() if waves_cnt > 0: resp.status = falcon.HTTP_403 return session.delete(year) session.commit() req.context['result'] = {} except SQLAlchemyError: session.rollback() raise finally: session.close()
def delete(self, id): repo = session.query(Repo).filter(Repo.id == id).first() if not repo: abort(404, message="[ERROR] - Repo {} doesn't exist".format(id)) session.delete(repo) session.commit() return {}, 204
def delete(self, id): team = session.query(Team).filter(Team.id == id).first() if not team: abort(404, message="Team {} does not exist".format(id)) session.delete(team) session.commit() return 204
def delete(self, id): student = session.query(Student).filter(Student.id == id).first() if not student: abort(404, message="Student {} doesn't exist".format(id)) session.delete(student) session.commit() return {}, 204
def delete(tag_name, tag_group_name, language_code): success = True error_msg = None tag_group_id = TagGroupModel.select_tag_group_id_by_tag_group_name( tag_group_name) language_id = LanguageModel.select_language_id_by_code(language_code) try: tag = session.\ query(TagModel).\ filter(TagModel.name == tag_name, TagModel.tag_group_id == tag_group_id, TagModel.language_id == language_id).\ one() session.delete(tag) session.commit() except (connector.Error, SQLAlchemyError) as e: session.rollback() success = False error_msg = e.__cause__ finally: session.close() return success, error_msg
def on_delete(self, req, resp, id): user = req.context['user'] try: achievement = session.query(model.Achievement).get(id) except SQLAlchemyError: session.rollback() raise if (not user.is_logged_in()) or (not user.is_admin()): req.context['result'] = { 'errors': [ { 'status': '401', 'title': 'Unauthorized', 'detail': u'Smazání trofeje může provést pouze administrátor.' } ] } resp.status = falcon.HTTP_400 return if not achievement: req.context['result'] = { 'errors': [ { 'status': '404', 'title': 'Not Found', 'detail': u'Trofej s tímto ID neexsituje.' } ] } resp.status = falcon.HTTP_404 return try: session.delete(achievement) session.commit() except SQLAlchemyError: session.rollback() raise finally: session.close() req.context['result'] = {}
def delete(id): poi = session.query(InterestPoint).filter(InterestPoint.id == id).first() if not poi: abort(404, message="poi {} doesn't exist".format(id)) session.delete(poi) session.commit() return {}, 204
def delete(self, id: int) -> dict: ingredient = session.query(Ingredient).get(id) session.delete(ingredient) session.commit() response = BasicResponse(None) return BasicResponseSchema().dump(response)
def delete(self, brand_id): brand = session.query(Brand).filter(Brand.id == brand_id).first() if not brand: abort(404, message="Brand {} doesn't exist".format(id)) session.delete(brand) session.commit() return {}, 204
def on_delete(self, req, resp, id): user = req.context['user'] try: user_db = session.query(model.User).get(id) except SQLAlchemyError: session.rollback() raise if (not user.is_logged_in()) or (not user.is_admin()): resp.status = falcon.HTTP_400 return if not user_db: resp.status = falcon.HTTP_404 return profile = session.query(model.Profile).get(id) try: if profile: session.delete(profile) session.delete(user_db) session.commit() except SQLAlchemyError: session.rollback() raise finally: session.close() req.context['result'] = {}
def delete(self, id): quiz = session.query(Quiz).filter(Quiz.id == id).first() if not quiz: abort(404, message="Quiz {} does not exist".format(id)) session.delete(quiz) session.commit() return {}, 204
def _process_achievements(self, corr): a_old = util.achievement.ids_list(util.achievement.per_task(corr['user'], corr['task_id'])) a_new = corr['achievements'] if a_old != a_new: # achievementy se nerovnaji -> proste smazeme vsechny dosavadni a pridame do db ty, ktere nam prisly for a_id in a_old: try: ach = session.query(model.UserAchievement).get((corr['user'], a_id)) if ach.task_id == corr['task_id']: session.delete(ach) session.commit() except: session.rollback() raise for a_id in a_new: try: ua = model.UserAchievement(user_id=corr['user'], achievement_id=a_id, task_id=corr['task_id']) session.add(ua) session.commit() except: session.rollback() raise finally: session.close()
def on_delete(self, req, resp, id): user = req.context['user'] if (not user.is_logged_in()) or (not user.is_org()): req.context['result'] = { 'errors': [{ 'status': '401', 'title': 'Unauthorized', 'detail': 'Smazat článek může pouze organizátor.' }] } resp.status = falcon.HTTP_400 return try: article = session.query(model.Article).get(id) if article is None: req.context['result'] = { 'errors': [{ 'status': '404', 'title': 'Not Found', 'detail': 'Článek s tímto ID neexistuje.' }] } resp.status = falcon.HTTP_404 return session.delete(article) session.commit() req.context['result'] = {} except SQLAlchemyError: session.rollback() raise finally: session.close()
def delete(self, id): record = session.query(Record).filter(Record.id == id).first() if not record: abort(404, message="Record {} doesn't exist".format(id)) session.delete(record) session.commit() return {}, 204
def delete(self, id): todo = session.query(Todo).filter(Todo.id == id).first() if not todo: abort(404, message="Todo {} doesn't exist".format(id)) session.delete(todo) session.commit() return {}, 204
def delete(self, year): temperature = session.query(Temperature).filter(Temperature.year == year).first() if not temperature: abort(404, message="Temperature {} doesn't exist".format(year)) session.delete(temperature) session.commit() return {}, 204
def delete(self, card_id, tag_id): cardtags = session.query(CardTag).filter(CardTag.card_id == card_id).filter(CardTag.tag_id == tag_id).first() if not cardtags: abort(404, message="Relation [card:{}, tag:{}] doesn't exist".format(card_id, tag_id)) session.delete(cardtags) session.commit() return {}, 204
def on_delete(self, req, resp, id): try: user = req.context['user'] # Vlnu mohou smazat jen admini if (not user.is_logged_in()) or (not user.is_admin()): resp.status = falcon.HTTP_400 return wave = session.query(model.Wave).get(id) if wave is None: resp.status = falcon.HTTP_404 return # Smazat lze jen neprazdnou vlnu. tasks_cnt = session.query(model.Task).filter(model.Task.wave == wave.id).count() if tasks_cnt > 0: resp.status = falcon.HTTP_403 return session.delete(wave) session.commit() req.context['result'] = {} except SQLAlchemyError: session.rollback() raise finally: session.close()
def delete(self, id): cat = session.query(Cat).get(id) if not cat: abort(404, message="Cat {} does not exist".format(id)) session.delete(cat) session.commit() return cat
def delete(self, id): user = session.query(User).filter(User.id == id).first() if not user: abort(404, message="User {} does not exist".format(id)) session.delete(user) session.commit() return 204
def delete(self, spot_id): spot = session.query(SportSpot).filter(SportSpot.id == spot_id).first() if not spot: abort(404, message="Spot {} doesn't exist".format(spot_id)) session.delete(spot) session.commit() return {}, 204
def delete(self, id): user = session.query(User).filter(User.id == id).first() if not user: abort(404, message="User {} does not exist".format(id)) session.delete(user) session.commit() return {}, 204
def delete(self, username): user = session.query(User).filter(User.username == username).first() if not user: abort(404, message="user {} doesn't exist".format(username)) session.delete(user) session.commit() return {}, 204
def delete(self, id): link = session.query(Link).filter(Link.id == id).first() if not link: abort(404, message="Link {} doesn't exist".format(id)) session.delete(link) session.commit() return {}, 204
def on_delete(self, req, resp, id): """Delete feedback""" try: user = req.context['user'] if not user.is_logged_in(): resp.status = falcon.HTTP_400 return feedback = session.query(model.Feedback).get((user.get_id(), id)) if feedback is None: req.context['result'] = { 'errors': [{ 'status': '404', 'title': 'Not found', 'detail': 'Feedback s tímto ID neexistuje.' }] } resp.status = falcon.HTTP_404 return session.delete(feedback) session.commit() req.context['result'] = {} except SQLAlchemyError: session.rollback() raise finally: session.close()
def delete(self, id): user = session.query(User).filter(User.id == id).first() if not user: abort(404, message="Usuario {} nao encontrado".format(id)) session.delete(user) session.commit() return {}, 204
def _process_achievements(self, corr): """ PUT: pridavani a mazani achievementu """ a_old = util.achievement.ids_list( util.achievement.per_task(corr['user'], corr['task_id'])) a_new = corr['achievements'] if a_old != a_new: # achievementy se nerovnaji -> proste smazeme vsechny dosavadni # a pridame do db ty, ktere nam prisly. for a_id in a_old: try: ach = session.query(model.UserAchievement).\ get((corr['user'], a_id)) if ach.task_id == int(corr['task_id']): session.delete(ach) session.commit() except SQLAlchemyError: session.rollback() raise for a_id in a_new: try: ua = model.UserAchievement(user_id=corr['user'], achievement_id=a_id, task_id=corr['task_id']) session.add(ua) session.commit() except SQLAlchemyError: session.rollback() raise finally: session.close()
def _process_thread(self, corr): """ PUT: propojeni diskuzniho vlakna komentare """ curr_thread = util.task.comment_thread(corr['task_id'], corr['user']) if (corr['comment'] is not None) and (curr_thread is None): # pridavame diskuzni vlakno try: comment = model.SolutionComment(thread=corr['comment'], user=corr['user'], task=corr['task_id']) session.add(comment) session.commit() except SQLAlchemyError: session.rollback() raise if (corr['comment'] is None) and (curr_thread is not None): # mazeme diskuzni vlakno try: comment = session.query(model.SolutionComment).\ get((curr_thread, corr['user'], corr['task_id'])) session.delete(comment) session.commit() except SQLAlchemyError: session.rollback() raise
def on_delete(self, req, resp, id): try: user = req.context['user'] # Vlnu mohou smazat jen admini if (not user.is_logged_in()) or (not user.is_admin()): resp.status = falcon.HTTP_400 return wave = session.query(model.Wave).get(id) if wave is None: resp.status = falcon.HTTP_404 return # Smazat lze jen neprazdnou vlnu. tasks_cnt = session.query(model.Task).\ filter(model.Task.wave == wave.id).\ count() if tasks_cnt > 0: resp.status = falcon.HTTP_403 return session.delete(wave) session.commit() req.context['result'] = {} except SQLAlchemyError: session.rollback() raise finally: session.close()
def update_clients(): clients_opts = {} for client in set(map(lambda k: k.rsplit('_', 1)[0], request.form.keys())): clients_opts[client] = { k.rsplit('_', 1)[1]: v for k, v in filter(lambda (k, v): k.startswith(client), request.form.iteritems()) } app.logger.debug(clients_opts) for client, opts in clients_opts.iteritems(): prefs = ClientPrefs.query.get( (uuid.UUID(session.get('userid')), client)) if 'delete' in opts and opts['delete'] in [ 'on', 'true', 'checked', 'selected', '1' ]: db_sess.delete(prefs) continue prefs.format = opts[ 'format'] if 'format' in opts and opts['format'] else None prefs.bitrate = int( opts['bitrate']) if 'bitrate' in opts and opts['bitrate'] else None db_sess.commit() flash('Clients preferences updated.') return user_profile()
def delete(self, student_id): args = delete_parser.parse_args() student = session.query(StudentModel).filter( StudentModel.student_id == student_id).first() course = session.query(CourseModel).filter( CourseModel.crn == args['crn']).first() assessments = session.query(AssessmentModel).filter( AssessmentModel.crn == args['crn'], AssessmentModel.student_id == student_id).all() # Abort if not course owner if course.faculty.faculty_id != current_identity.faculty_id: abort( 403, message= "You are not authorized to delete students from this course.") #remove student from the course #remove any assessments for that student for that course if student and course: #student and course must exist if student in course.students: course.students.remove(student) for each_assessment in assessments: for each_score in each_assessment.scores: session.delete( each_score ) #deletes the scores property for deletion session.delete( each_assessment) #loops and deletes each assessment session.commit() return {}, 204 #Delete successful else: abort(404, message="Delete unsuccessful")
def delete(self, dish_id): dish = session.query(Dish).filter(Dish.dish_id == dish_id).first() if not dish: abort(404, message="dish {} doesn't exist".format(dish_id)) session.delete(dish) session.commit() return {}, 204
def delete(self, id): section = session.query(Section).filter(Section.id == id).first() session.delete(section) session.commit() return {}, 200
def delete(self, id): note = session.query(Note).filter(Note.id == id).first() if not note: abort(404, message="Note {} doesn't exist".format(id)) session.delete(note) session.commit() return {}, 204
def delete(self, id): post = session.query(Post).filter(Post.id == id).first() if not post: abort(404, message="Postagem {} nao encontrada".format(id)) session.delete(post) session.commit() return {}, 204
def on_delete(self, req, resp, id): """ Smazani ulohy """ try: user = req.context['user'] # Ulohu mohou smazat jen admini if (not user.is_logged_in()) or (not user.is_admin()): resp.status = falcon.HTTP_400 return task = session.query(model.Task).get(id) if task is None: resp.status = falcon.HTTP_404 return # Ulohu lze smazat jen pred casem zverejneni vlny wave = session.query(model.Wave).get(task.wave) if datetime.datetime.utcnow() > wave.time_published: resp.status = falcon.HTTP_403 return execs = session.query(model.CodeExecution).\ join( model.Module, model.Module.id == model.CodeExecution.module ).\ filter(model.Module.task == id).all() for _exec in execs: session.delete(_exec) evals = session.query(model.Evaluation).\ join(model.Module, model.Module.id == model.Evaluation.module).\ filter(model.Module.task == id).all() for _eval in evals: session.delete(_eval) session.query(model.Module).\ filter(model.Module.task == id).delete() thread = session.query(model.Thread).get(task.thread) prer = task.prerequisite_obj if prer is not None: session.delete(task.prerequisite_obj) session.delete(task) session.commit() if thread is not None: session.delete(thread) session.commit() req.context['result'] = {} except SQLAlchemyError: session.rollback() raise finally: session.close()
def delete(self, id): group = session.query(Group).filter(Group.id == id).first() if not group: abort(404, message="Group {} doesn't exist".format(id)) session.delete(group) session.commit() return group, 200
def delete(self, id): if id is None: raise Exception("id required to delete data") else: profile = ProfileModel.query.get(id) session.delete(profile) session.commit() return {'message': 'deleted Successfully', 'id': id}
def user_delete(name): user = session.query(User).filter(User.name == name).first() if not user: print >>sys.stderr, 'No such user' else: session.delete(user) session.commit() print "User '{}' deleted".format(name)
def delete(uid): status, user = UserManager.get(uid) if status != UserManager.SUCCESS: return status session.delete(user) session.commit() return UserManager.SUCCESS
def delete_playlist(): status, res = get_entity(request, Playlist) if not status: return res if res.user_id != request.user.id and not request.user.admin: return request.error_formatter(50, "You're not allowed to delete a playlist that isn't yours") session.delete(res) session.commit() return request.formatter({})
def update_tokens(): try: # refresh token nechavame v databazi jeste den, aby se uzivatel mohl znovu prihlasit automaticky # (napriklad po uspani pocitace) tokens = session.query(model.Token).all() tokens = filter(lambda token: datetime.datetime.utcnow() > token.expire+datetime.timedelta(days=1), tokens) for token in tokens: session.delete(token) session.commit() except: session.rollback() raise
def on_delete(self, req, resp, id): try: submittedFile = self._get_submitted_file(req, resp, id) if submittedFile: # Kontrola casu (soubory lze mazat jen pred deadline) eval_id = submittedFile.evaluation task = session.query(model.Task).\ join(model.Module, model.Module.task == model.Task.id).\ join(model.Evaluation, model.Evaluation.module == model.Module.id).\ filter(model.Evaluation.id == submittedFile.evaluation).first() if task.time_deadline < datetime.datetime.utcnow(): req.context['result'] = { 'result': 'error', 'error': u'Nelze smazat soubory po termínu odevzdání úlohy' } return try: os.remove(submittedFile.path) evaluation = session.query(model.Evaluation).get(eval_id) if evaluation: evaluation.full_report += str(datetime.datetime.now()) + " : removed file " + submittedFile.path + '\n' session.delete(submittedFile) session.commit() # Pokud resitel odstranil vsechny soubory, odstranime evaluation if evaluation: files_cnt = session.query(model.SubmittedFile).filter(model.SubmittedFile.evaluation == eval_id).count() if files_cnt == 0: session.delete(evaluation) session.commit() req.context['result'] = { 'status': 'ok' } except OSError: req.context['result'] = { 'status': 'error', 'error': u'Soubor se nepodařilo odstranit z filesystému' } return except exc.SQLAlchemyError: req.context['result'] = { 'status': 'error', 'error': u'Záznam o souboru se nepodařilo odstranit z databáze' } return else: if resp.status == falcon.HTTP_404: req.context['result'] = { 'status': 'error', 'error': u'Soubor nenalezen na serveru' } elif resp.status == falcon.HTTP_403: req.context['result'] = { 'status': 'error', 'error': u'K tomuto souboru nemáte oprávnění' } else: req.context['result'] = { 'status': 'error', 'error': u'Soubor se nepodařilo získat' } resp.status = falcon.HTTP_200 except SQLAlchemyError: session.rollback() raise finally: session.close()
def _refresh(self, req, resp): refresh_token = req.get_param('refresh_token') try: token = session.query(model.Token).filter( model.Token.refresh_token == refresh_token).first() if token: session.delete(token) req.context['result'] = auth.OAuth2Token(token.user).data else: req.context['result'] = {'error': Error.UNAUTHORIZED_CLIENT} resp.status = falcon.HTTP_400 except SQLAlchemyError: session.rollback() raise
def deleteMenuItem(restaurant_id, menuitem_id): restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one() creator = getUserInfo(restaurant.user_id) if ('username' not in login_session) or (creator.id != login_session['user_id']): return redirect(url_for('showLogin')) menuitem = session.query(MenuItem).filter_by(id=menuitem_id).one() if request.method == 'POST': flashMessage = 'Menu item: %s deleted!' % menuitem.name session.delete(menuitem) session.commit() flash(flashMessage) return redirect(url_for('restaurantMenu', restaurant_id=restaurant_id)) else: return render_template( 'delete-menu-item.html', item=menuitem)
def onRemoveT(self): answer = QMessageBox.question(self, 'Remove Topic', "This operation will remove this topic and it's questions.") if answer == QMessageBox.No: return row = self.lstTopics.currentRow() id = self.lstTopics.currentItem().statusTip() record = session.query(Topic).filter(Topic.id == id) if record: record.delete(synchronize_session=False) self.lstTopics.takeItem(row) self.lstQuestions.clear() qs = session.query(Question).filter(Question.topic_id == id).all() for q in qs: session.delete(q) session.commit() self.btnRemoveT.setEnabled(False)
def on_get(self, req, resp): try: if not req.context['user'].is_logged_in(): return token = session.query(model.Token).filter(model.Token.access_token == req.context['user'].token).first() if not token: return session.delete(token) session.commit() except SQLAlchemyError: session.rollback() raise finally: session.close()
def on_post(self, req, resp): data = json.loads(req.stream.read()) try: existing_user = session.query(model.User).filter(model.User.email == data['email']).first() if existing_user != None: req.context['result'] = { 'error': "duplicate_user" } return except SQLAlchemyError: session.rollback() raise try: if not 'nick_name' in data: data['nick_name'] = "" user = model.User(email=data['email'], password=auth.get_hashed_password(data['password']), first_name=data['first_name'], last_name=data['last_name'], nick_name=data['nick_name'], sex=data['gender'], short_info=data["short_info"]) session.add(user) session.commit() except: session.rollback() req.context['result'] = { 'error': "Nelze vytvořit uživatele, kontaktuj prosím orga." } raise try: profile = model.Profile(user_id=user.id, addr_street=data['addr_street'], addr_city=data['addr_city'], addr_zip=data['addr_zip'], addr_country=data['addr_country'],\ school_name=data['school_name'], school_street=data['school_street'], school_city=data['school_city'], school_zip=data['school_zip'], school_country=data['school_country'], school_finish=int(data['school_finish']),\ tshirt_size=data['tshirt_size'].upper()) except: session.delete(user) req.context['result'] = { 'error': "Nelze vytvořit profil, kontaktuj prosím orga." } raise try: session.add(profile) session.commit() except: session.rollback() raise try: util.mail.send(user.email, u'[KSI-WEB] Potvrzení registrace do Korespondenčního semináře z informatiky', u'Ahoj!<br/>Vítáme tě v Korespondenčním semináři z informatiky Fakulty informatiky Masarykovy univerzity. Nyní můžeš začít řešit naplno. Stačí se přihlásit na https://ksi.fi.muni.cz pomocí e-mailu a zvoleného hesla. Přejeme ti hodně úspěchů při řešení semináře!<br/><br/>KSI') except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback, file=sys.stderr) session.close()
def update_clients(): clients_opts = {} for client in set(map(lambda k: k.rsplit('_', 1)[0],request.form.keys())): clients_opts[client] = { k.rsplit('_', 1)[1]: v for k, v in filter(lambda (k, v): k.startswith(client), request.form.iteritems()) } app.logger.debug(clients_opts) for client, opts in clients_opts.iteritems(): prefs = ClientPrefs.query.get((uuid.UUID(session.get('userid')), client)) if 'delete' in opts and opts['delete'] in [ 'on', 'true', 'checked', 'selected', '1' ]: db_sess.delete(prefs) continue prefs.format = opts['format'] if 'format' in opts and opts['format'] else None prefs.bitrate = int(opts['bitrate']) if 'bitrate' in opts and opts['bitrate'] else None db_sess.commit() flash('Clients preferences updated.') return user_profile()
def on_put(self, req, resp, id): try: user = req.context['user'] # Upravovat rocniky mohou jen ADMINI if (not user.is_logged_in()) or (not user.is_admin()): resp.status = falcon.HTTP_400 return data = json.loads(req.stream.read())['year'] year = session.query(model.Year).get(id) if year is None: resp.status = falcon.HTTP_404 return year.id = data['index'] year.year = data['year'] year.sealed = data['sealed'] year.point_pad = data['point_pad'] # Aktualizace aktivnich orgu orgs = session.query(model.ActiveOrg).\ filter(model.ActiveOrg.year == year.id).all() for i in range(len(orgs)-1, -1, -1): if str(orgs[i].org) in data['active_orgs']: data['active_orgs'].remove(str(orgs[i].org)) del orgs[i] for org in orgs: session.delete(org) for user_id in data['active_orgs']: org = model.ActiveOrg(org=user_id, year=year.id) session.add(org) session.commit() except SQLAlchemyError: session.rollback() raise finally: session.close() self.on_get(req, resp, id)
def restaurantDelete(restaurant_id): restaurantToDelete = session.query(Restaurant).filter_by(id=restaurant_id).one() creator = getUserInfo(restaurantToDelete.user_id) if (creator.id != login_session['user_id']): return '''<script> function myFunction(){ alert('You are not authorized'); location.href='/login';} </script> <body onload='myFunction();'> ''' restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one() if request.method == 'POST': flashMessage = 'Restaurant: %s deleted!' % restaurant.name session.delete(restaurant) session.commit() flash(flashMessage) return redirect(url_for('restaurantList')) else: return render_template('delete-restaurant.html', restaurant=restaurant)
def delete_module(module): # Ve vsech techto slozkach muze byt neco k modulu module_paths = [\ "data/modules/"+str(module.id),\ "data/programming-modules/"+str(module.id),\ "data/text-modules/"+str(module.id) ] for path in module_paths: if os.path.isdir(path): try: shutil.rmtree(path, ignore_errors=True) except: pass try: session.delete(module) session.commit() except: session.rollback() raise
def story(story_id): user = None if 'username' in session: user = session['username'] if request.method=='GET': story = dbsession.query(Story).filter_by(id=story_id).first() if story is None: flash("Story does not exist!") return redirect(url_for('hello')) else: return render_template('story.html', story=story, user=user) elif request.method=='POST': if user == request.form['user']: story = dbsession.query(Story).filter_by(id=story_id).first() dbsession.delete(story) dbsession.commit() else: flash("Cannot delete story without permission") return redirect(url_for('hello'))
def story(story_id): user = None if "username" in session: user = session["username"] if request.method == "GET": story = dbsession.query(Story).filter_by(id=story_id).first() if story is None: flash("Story does not exist!") return redirect(url_for("hello")) else: return render_template("story.html", story=story, user=user) elif request.method == "POST": if user == request.form["user"]: story = dbsession.query(Story).filter_by(id=story_id).first() dbsession.delete(story) dbsession.commit() else: flash("Cannot delete story without permission") return redirect(url_for("hello"))
def on_delete(self, req, resp, id): try: user = req.context['user'] if (not user.is_logged_in()) or (not user.is_org()): resp.status = falcon.HTTP_400 return post = session.query(model.Post).get(id) if post is None: resp.status = falcon.HTTP_404 return session.delete(post) session.commit() req.context['result'] = {} except SQLAlchemyError: session.rollback() raise finally: session.close()
def delete(uid, scanner): status, folder = FolderManager.get(uid) if status != FolderManager.SUCCESS: return status if not folder.root: return FolderManager.NO_SUCH_FOLDER session.delete(folder) paths = session.query(Folder.path.like(folder.path + os.sep + '%')).delete() #for f in paths: #if not any (p.path in f.path for p in paths) and not f.root: #app.logger.debug('Deleting path with no parent: ' + f.path) #self.__session.delete(f) scanner.prune(folder) session.commit() return FolderManager.SUCCESS
def delete(uid): status, folder = FolderManager.get(uid) if status != FolderManager.SUCCESS: return status if not folder.root: return FolderManager.NO_SUCH_FOLDER # delete associated tracks and prune empty albums/artists for artist in Artist.query.all(): for album in artist.albums[:]: for track in filter(lambda t: t.root_folder.id == folder.id, album.tracks): album.tracks.remove(track) session.delete(track) if len(album.tracks) == 0: artist.albums.remove(album) session.delete(album) if len(artist.albums) == 0: session.delete(artist) def cleanup_folder(folder): for f in folder.children: cleanup_folder(f) session.delete(folder) cleanup_folder(folder) session.commit() return FolderManager.SUCCESS