def on_get(self, req, resp): try: user = req.context['user'] year = req.context['year'] if (not user.is_logged_in()) or (not user.is_org()): req.context['result'] = { 'errors': [ { 'status': '401', 'title': 'Unauthorized', 'detail': u'Přístup k opravovátku mají pouze organizátoři.' } ] } resp.status = falcon.HTTP_400 return tasks = session.query(model.Task).\ join(model.Wave, model.Wave.id == model.Task.wave).\ filter(model.Wave.year == year).all() waves = session.query(model.Wave).\ filter(model.Wave.year == year).\ join(model.Task, model.Task.wave == model.Wave.id).all() users = session.query(model.User) users = set(util.user.active_in_year(users, year).all()) users |= set(session.query(model.User).\ join(model.Task, model.Task.author == model.User.id).all()) req.context['result'] = { 'correctionsInfos': [ util.correctionInfo.task_to_json(task) for task in tasks ], 'waves': [ util.wave.to_json(wave) for wave in waves ], 'users': [ util.correctionInfo.user_to_json(user) for user in users ] } except SQLAlchemyError: session.rollback() raise finally: session.close()
def restaurantMenu(restaurant_id): restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one() creator = getUserInfo(restaurant.user_id) appetizers = session.query(MenuItem).filter_by(restaurant_id=restaurant.id, course="Appetizers") main_dishes = session.query(MenuItem).filter_by(restaurant_id=restaurant.id, course="Main Dish") beverages = session.query(MenuItem).filter_by(restaurant_id=restaurant.id, course="Beverages").all() desserts = session.query(MenuItem).filter_by(restaurant_id=restaurant.id, course="Desserts") if 'username' not in login_session: return render_template( 'restaurant-menu-public.html', restaurant=restaurant, appetizers=appetizers, main_dishes=main_dishes, beverages=beverages, desserts=desserts, creatorPicture=creator.picture ) else: isCreator = login_session['user_id'] == creator.id return render_template( 'restaurant-menu.html', restaurant=restaurant, appetizers=appetizers, main_dishes=main_dishes, beverages=beverages, desserts=desserts, isCreator=isCreator, creatorPicture=creator.picture )
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 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 get(self, user_id): user = session.query(User).filter(User.id == user_id).first() if not user: abort(404, message="User {} doesn't exist".format(user_id)) groups = session.query(Group).join(Group.users).filter(User.id == user_id).all() return groups, 200
def on_get(self, req, resp, id): try: user = req.context['user'] user_id = req.context['user'].get_id() if req.context['user'].is_logged_in() else None post = session.query(model.Post).get(id) if post is None: resp.status = falcon.HTTP_404 return thread = session.query(model.Thread).get(post.thread) if thread is None: resp.status = falcon.HTTP_404 return # Kontrola pristupu k prispevkum: # a) K prispevkum v eval vlakne mohou pristoupit jen orgove a jeden resitel # b) K ostatnim neverejnym prispevkum mohou pristoupit jen orgove. if not thread.public and ((not user.is_logged_in()) or (not user.is_org() and not util.thread.is_eval_thread(user.id, thread.id))): resp.status = falcon.HTTP_400 return req.context['result'] = { 'post': util.post.to_json(post, user_id) } except SQLAlchemyError: session.rollback() raise finally: session.close()
def on_post(self, req, resp, id): try: user = req.context['user'] if not user.is_logged_in(): resp.status = falcon.HTTP_400 return data = json.loads(req.stream.read())['content'] module = session.query(model.Module).get(id) if not module: resp.status = falcon.HTTP_400 return task_status = util.task.status(session.query(model.Task).get(module.task), user) if task_status == util.TaskStatus.LOCKED: resp.status = falcon.HTTP_400 return req.context['result'] = util.programming.run(module, user.id, data) except SQLAlchemyError: session.rollback() raise finally: session.close()
def on_get(self, req, resp, id): try: user = req.context['user'] user_id = req.context['user'].id if req.context['user'].is_logged_in() else None thread = session.query(model.Thread).get(id) if not thread: req.context['result'] = { 'errors': [ { 'status': '404', 'title': 'Not Found', 'detail': u'Toto vlákno neexistuje.' } ] } resp.status = falcon.HTTP_404 return if (not thread) or (not thread.public and not (user.is_org() or util.thread.is_eval_thread(user.id, thread.id))): req.context['result'] = { 'errors': [ { 'status': '401', 'title': 'Unauthorized', 'detail': u'Přístup k vláknu odepřen.' } ] } resp.status = falcon.HTTP_400 return # Pocet vsech prispevku posts_cnt = session.query(model.Post).filter(model.Post.thread == thread.id).count() # Pocet neprectenych prispevku if not user.is_logged_in(): unread_cnt = posts_cnt else: visit = session.query(model.ThreadVisit).filter(model.ThreadVisit.user == user.id, model.ThreadVisit.thread == thread.id).first() if visit: unread_cnt = session.query(model.Post).filter(model.Post.thread == thread.id, model.Post.published_at > visit.last_visit).count() else: unread_cnt = posts_cnt req.context['result'] = { 'thread': util.thread.to_json(thread, user_id, unread_cnt, posts_cnt) } except SQLAlchemyError: session.rollback() raise finally: session.close()
def on_post(self, req, resp, id): try: user = req.context['user'] # Kontrola existence ulohy task = session.query(model.Task).get(id) if task is None: req.context['result'] = 'Neexistujici uloha' resp.status = falcon.HTTP_404 return # Kontrola existence git_branch a git_path if (task.git_path is None) or (task.git_branch is None): req.context['result'] = 'Uloha nema zadanou gitovskou vetev nebo adresar' resp.status = falcon.HTTP_400 return if task.git_branch == "master": req.context['result'] = 'Uloha je j*z ve vetvi master' resp.status = falcon.HTTP_400 return wave = session.query(model.Wave).get(task.wave) # Merge mohou provadet pouze administratori a garant vlny if (not user.is_logged_in()) or ((not user.is_admin()) and (user.id != wave.garant)): req.context['result'] = 'Nedostatecna opravneni' resp.status = falcon.HTTP_400 return # Kontrola zamku lock = util.lock.git_locked() if lock: req.context['result'] = 'GIT uzamcen zámkem '+lock + "\nNekdo momentalne provadi akci s gitem, opakujte prosim akci za 20 sekund." resp.status = falcon.HTTP_409 return try: mergeLock = LockFile(util.admin.taskMerge.LOCKFILE) mergeLock.acquire(60) # Timeout zamku je 1 minuta # Fetch repozitare repo = git.Repo(util.git.GIT_SEMINAR_PATH) if task.git_branch in repo.heads: # Cannot delete branch we are on repo.git.checkout("master") repo.git.branch('-D', task.git_branch) task.git_branch = 'master' session.commit() resp.status = falcon.HTTP_200 finally: mergeLock.release() except SQLAlchemyError: session.rollback() raise finally: session.close()
def search_id3(): query, artist_count, artist_offset, album_count, album_offset, song_count, song_offset = map( request.args.get, [ 'query', 'artistCount', 'artistOffset', 'albumCount', 'albumOffset', 'songCount', 'songOffset' ]) try: artist_count = int(artist_count) if artist_count else 20 artist_offset = int(artist_offset) if artist_offset else 0 album_count = int(album_count) if album_count else 20 album_offset = int(album_offset) if album_offset else 0 song_count = int(song_count) if song_count else 20 song_offset = int(song_offset) if song_offset else 0 except: return request.error_formatter(0, 'Invalid parameter') if not query: return request.error_formatter(10, 'Missing query parameter') artist_query = session.query(Artist).filter(Artist.name.contains(query)).slice(artist_offset, artist_offset + artist_count) album_query = session.query(Album).filter(Album.name.contains(query)).slice(album_offset, album_offset + album_count) song_query = session.query(Track).filter(Track.title.contains(query)).slice(song_offset, song_offset + song_count) return request.formatter({ 'searchResult2': { 'artist': [ a.as_subsonic_artist(request.user) for a in artist_query ], 'album': [ a.as_subsonic_album(request.user) for a in album_query ], 'song': [ t.as_subsonic_child(request.user) for t in song_query ] }})
def upsert_contributors(o_data, r_data): organization = session.query(Organization).filter(Organization.id==o_data.id).first() contributors = set() for r_item in r_data: if not r_item.fork: c_data = r_item.get_contributors() repo_contributors = [] for c_item in c_data: check_rate_limit(c_item) contributor = p_formatter(c_item) contributor = upsert(model=Person, unique_key='id', item=contributor) contributors.add(contributor) repo_contributors.append(contributor) repository = session.query(Repository).filter(Repository.id==r_item.id).first() repository.contributors = repo_contributors session.add(repository) session.commit() contributors = list(contributors) organization.contributors = contributors try: session.add(organization) session.commit() except: session.rollback()
def storynew(): if 'username' in session: user = session['username'] form = StoryForm() if form.validate_on_submit(): uid = dbsession.query(User.id).filter_by(name=user).first() newstory = Story(form.title.data) newstory.text = markdown.markdown(form.body.data) newstory.uid = uid[0] newstory.adult = form.adult.data tagslist = form.tags.data tagslist = tagslist.split(',') for tagitem in tagslist: tagitem = tagitem.strip() tagitem = tagitem.lower() tag = dbsession.query(Tag).filter_by(tagname=tagitem).first() if tag is None: tag = Tag(tagitem) newstory.tags.append(tag) dbsession.add(newstory) dbsession.commit() return redirect("~"+user) return render_template("storynew.html", form=form) else: return render_template("storynew.html")
def get(self, identity): session = self.application.db_session if identity != '': client = session.query(ClientInfo).filter(ClientInfo.identity==identity).first() client_info = { 'identity': client.identity, 'name': client.name, 'type': client.type, 'ip_addr': client.ip_addr, 'mac_addr': client.mac_addr, 'status': client.status, 'update_time': str(client.update_time), } self.write(json.dumps(client_info)) return response = [] for client in session.query(ClientInfo).all(): client_info = { 'identity': client.identity, 'name': client.name, 'type': client.type, 'ip_addr': client.ip_addr, 'mac_addr': client.mac_addr, 'status': client.status, 'update_time': str(client.update_time), } response.append(client_info) self.write(json.dumps(response))
def new_search(): query, artist_count, artist_offset, album_count, album_offset, song_count, song_offset = map( request.args.get, [ 'query', 'artistCount', 'artistOffset', 'albumCount', 'albumOffset', 'songCount', 'songOffset' ]) try: artist_count = int(artist_count) if artist_count else 20 artist_offset = int(artist_offset) if artist_offset else 0 album_count = int(album_count) if album_count else 20 album_offset = int(album_offset) if album_offset else 0 song_count = int(song_count) if song_count else 20 song_offset = int(song_offset) if song_offset else 0 except: return request.error_formatter(0, 'Invalid parameter') if not query: return request.error_formatter(10, 'Missing query parameter') artist_query = session.query(Folder).filter(~ Folder.tracks.any(), Folder.path.contains(query)).slice(artist_offset, artist_offset + artist_count) album_query = session.query(Folder).filter(Folder.tracks.any(), Folder.path.contains(query)).slice(album_offset, album_offset + album_count) song_query = sesion.query(Track).filter(Track.title.contains(query)).slice(song_offset, song_offset + song_count) return request.formatter({ 'searchResult2': { 'artist': [ { 'id': a.id, 'name': a.name } for a in artist_query ], 'album': [ f.as_subsonic_child(request.user) for f in album_query ], 'song': [ t.as_subsonic_child(request.user) for t in song_query ] }})
def list_artists(): # According to the API page, there are no parameters? indexes = {} # Optimized query instead of using backrefs, is there a way to speed up the backref? c = session.query(Album.artist_id, func.count(Album.artist_id).label('c')).group_by(Album.artist_id).subquery(name='c') for artist in session.query(Artist.name, Artist.id, c.c.c.label('albums')).join(c).order_by(Artist.name).all(): index = artist.name[0].upper() if artist.name else '?' if index in map(str, xrange(10)): index = '#' elif index not in string.letters: index = '?' if index not in indexes: indexes[index] = [] indexes[index].append(artist) return request.formatter({ 'artists': { 'index': [ { 'name': k, 'artist': [ { 'id': a.id, 'name': a.name.strip(), 'albumCount': a.albums } for a in v ] } for k, v in sorted(indexes.iteritems()) ] } })
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 editMenuItem(restaurant_id, menuitem_id): restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one() creator = getUserInfo(restaurant.user_id) if 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': if request.form['name']: menuitem.name = request.form['name'] if request.form['description']: menuitem.description = request.form['description'] if request.form['price']: menuitem.price = request.form['price'] if request.form['course']: menuitem.course = request.form['course'] session.add(menuitem) session.commit() flash('Menu Item {0} Updated'.format(menuitem.name)) return redirect(url_for('restaurantMenu', restaurant_id=restaurant_id)) else: return render_template( 'edit-menu-item.html', restaurant_id=restaurant_id, menuitem_id=menuitem_id, item=menuitem, courses=constants.COURSES)
def newMenuItem(restaurant_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')) if request.method == 'POST': # File upload filename = "" file = request.files['image'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) newItem = MenuItem( course=request.form['course'], description=request.form['description'], name=request.form['name'], price=request.form['price'], restaurant_id=restaurant_id, user_id=login_session['user_id'], image=filename ) session.add(newItem) session.commit() flash('New Menu Item created!') return redirect(url_for('restaurantMenu', restaurant_id=restaurant_id)) else: restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one() return render_template( 'new-menu-item.html', restaurant=restaurant, courses=constants.COURSES)
def delete(self, user_id, group_id): user = session.query(User).filter(User.id == user_id).first() group = session.query(Group).filter(Group.id == group_id).first() if not (user or group): abort(404, message="user or group doesn't exist") group.users.remove(user) session.commit() return user, 200
def checkin(self,uid, bStatusDone=False): edit = session.query(Edits).filter(Edits.uid==uid).filter(Edits.rid==self.id).\ filter(Edits.date_in == None).first() edit.date_in = datetime.now() session.add(edit) session.commit() if bStatusDone: self.status="%s-done" % session.query(User).filter(User.id==uid).first().initials session.add(self) session.commit()
def search(): if request.method == "GET": flash("Please use the search box to search") return redirect(url_for("hello")) term = request.form["searchitem"] storylist = dbsession.query(Story).filter(Story.text.contains(term)).all() storylist[1:1] = dbsession.query(Story).filter(Story.title.contains(term)).all() storytagged = dbsession.query(Story).filter(Story.tags.any(Tag.tagname == term)).all() return render_template("search.html", storytagged=storytagged, term=term, storylist=storylist)
def fromName(cls, name): if name == 'Louis Amundson': name = 'Lou Amundson' elif name == 'Glenn Robinson III': name = 'Glenn Robinson' query = session.query(Player).filter_by(name=name) if query.count() == 0: query = session.query(Player).filter_by(name=name.replace('.', '')) if query.count() == 0: raise Exception("Could not find player with name %s" % name) return query[0]
def on_post(self, req, resp, id): try: user = req.context['user'] # Kontrola opravneni if (not user.is_logged_in()) or (not user.is_org()): req.context['result'] = 'Nedostatecna opravneni' resp.status = falcon.HTTP_400 return # Kontrola existence ulohy task = session.query(model.Task).get(id) if task is None: req.context['result'] = 'Neexistujici uloha' resp.status = falcon.HTTP_404 return # Zverejnene ulohy mohou deployovat pouze admini wave = session.query(model.Wave).get(task.wave) if (datetime.datetime.utcnow() > wave.time_published) and (not user.is_admin()): req.context['result'] = 'Po zverejneni ulohy muze deploy provest pouze administrator' resp.status = falcon.HTTP_404 return # Kontrola existence gitovske vetve a adresare v databazi if (task.git_branch is None) or (task.git_path is None): req.context['result'] = 'Uloha nema zadanou gitovskou vetev nebo adresar' resp.status = falcon.HTTP_400 return # Kontrola zamku lock = util.lock.git_locked() if lock: req.context['result'] = 'GIT uzamcen zamkem ' + lock + "\nNekdo momentalne provadi akci s gitem, opakujte prosim akci za 20 sekund." resp.status = falcon.HTTP_409 return # Stav na deploying je potreba nastavit v tomto vlakne task.deploy_status = 'deploying' session.commit() try: deployLock = LockFile(util.admin.taskDeploy.LOCKFILE) deployLock.acquire(60) # Timeout zamku je 1 minuta deployThread = threading.Thread(target=util.admin.taskDeploy.deploy, args=(task.id, deployLock, scoped_session(_session)), kwargs={}) deployThread.start() finally: deployLock.release() resp.status = falcon.HTTP_200 except SQLAlchemyError: session.rollback() raise finally: session.close()
def _max_points_per_wave(bonus=False): # Nevadi nam, kdyz points_per_task nektere ulohy nevrati (to budou ty, ktere nemaji modul) points_per_task = session.query(model.Module.task.label('id'), func.sum(model.Module.max_points).label('points')) if not bonus: points_per_task = points_per_task.filter(model.Module.bonus == False) points_per_task = points_per_task.group_by(model.Module.task).subquery() # points_per_wave return session.query(model.Wave.id.label('id'), func.sum(points_per_task.c.points).label('points'), func.count(model.Task).label('tasks_count')).\ outerjoin(model.Task, model.Task.wave == model.Wave.id).\ outerjoin(points_per_task, points_per_task.c.id == model.Task.id).\ group_by(model.Wave)
def tasks_corrected(): task_corrected = session.query(model.Task.id.label('task_id'), (func.count(model.Evaluation) > 0).label('notcorrected')).\ join(model.Module, model.Module.task == model.Task.id).\ join(model.Evaluation, model.Module.id == model.Evaluation.module).\ filter(model.Evaluation.evaluator == None, not_(model.Module.autocorrect)).\ group_by(model.Task).subquery() return [ r for (r, ) in session.query(model.Task.id).\ outerjoin(task_corrected, task_corrected.c.task_id == model.Task.id).\ filter(or_(task_corrected.c.notcorrected == False, task_corrected.c.notcorrected == None)) ]
def favestory(story_id): user = None if "username" in session: if request.method == "POST": user = session["username"] u = dbsession.query(User).filter_by(name=user).first() s = dbsession.query(Story).filter_by(id=story_id).first() u.faves.append(s) dbsession.add(u) dbsession.commit() flash("Fave'd story ") return redirect("/story/" + str(story_id))
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 best_scores(task_id): per_modules = session.query(model.User.id.label('user_id'), \ func.max(model.Evaluation.points).label('points')).\ join(model.Evaluation, model.Evaluation.user == model.User.id).\ filter(model.Module.task == task_id, 'points' is not None, model.Evaluation.ok).\ join(model.Module, model.Evaluation.module == model.Module.id).\ join(model.Task, model.Task.id == model.Module.task).\ filter(model.Task.evaluation_public).\ order_by(model.Evaluation.time).\ group_by(model.Evaluation.module, model.User).subquery() return session.query(model.User, func.sum(per_modules.c.points).label('sum')).join(per_modules, per_modules.c.user_id == model.User.id).filter(model.User.role == 'participant').group_by(per_modules.c.user_id).order_by(desc('sum')).slice(0, 5).all()
def checkout(self,uid): check = session.query(Edits).filter(Edits.uid==uid).filter(Edits.rid==self.id).\ filter(Edits.date_out != None).filter(Edits.date_in == None).first() if check: return "Record already checked out by %s" % session.query(User.name).filter(User.id==uid).first()[0] else: edit = Edits(uid,self.id) edit.date_out = datetime.now() edit.date_in = None session.add(edit) session.commit() #self.status="%s-done" % session.query(User).filter(id=uid).first().initials #session.add(self) return "Record checked out"
def to_json(module, user_id): module_json = _info_to_json(module) # Nejdriv zjistime, jestli mame nejake evaluations count = session.query(model.Evaluation.points).filter(model.Evaluation.user == user_id, model.Evaluation.module == module.id).\ join(model.Module, model.Module.id == model.Evaluation.module).\ join(model.Task, model.Task.id == model.Module.task).count() # Skore nejlepsiho evaluation, kterehoz (ok == True) best_status = session.query(func.max(model.Evaluation.points).label('points')).\ filter(model.Evaluation.user == user_id, model.Evaluation.module == module.id, model.Evaluation.ok).\ join(model.Module, model.Module.id == model.Evaluation.module).\ join(model.Task, model.Task.id == model.Module.task).\ filter(model.Task.evaluation_public).first() if count > 0: # ziskame nejlepsi evaluation a podle toho rozhodneme, jak je na tom resitel module_json['state'] = 'correct' if best_status.points is not None else 'incorrect' else: module_json['state'] = 'blank' module_json['score'] = module.id if best_status.points is not None else None try: if module.type == ModuleType.PROGRAMMING: prog = util.programming.to_json(json.loads(module.data), user_id) module_json['code'] = prog['default_code'] module_json['default_code'] = prog['default_code'] if not module.autocorrect: module_json['state'] = 'correct' if count > 0 else 'blank' elif module.type == ModuleType.QUIZ: module_json['questions'] = util.quiz.to_json(json.loads(module.data), user_id) elif module.type == ModuleType.SORTABLE: module_json['sortable_list'] = util.sortable.to_json(json.loads(module.data), user_id) elif module.type == ModuleType.GENERAL: module_json['state'] = 'correct' if count > 0 else 'blank' submittedFiles = session.query(model.SubmittedFile).\ join(model.Evaluation, model.SubmittedFile.evaluation == model.Evaluation.id).\ filter(model.Evaluation.user == user_id, model.Evaluation.module == module.id).all() submittedFiles = [ {'id': inst.id, 'filename': os.path.basename(inst.path)} for inst in submittedFiles ] module_json['submitted_files'] = submittedFiles elif module.type == ModuleType.TEXT: txt = util.text.to_json(json.loads(module.data), user_id) module_json['fields'] = txt['questions'] except Exception, e: module_json['description'] += "<pre><code><strong>Module parsing error:</strong><br>" + str(e) + "</code></pre>"
def post(self): args = parser.parse_args() name = args['name'] if name is None or name == '': abort(400, message="Couldn't create the name") if session.query(SPFH).filter_by(name=name).first() is not None: abort(404, message="Stock {} already exist".format(name)) spfh = SPFH.create(name) if spfh == None: abort(404, message="stock not found with {} as query".format(name)) session.add(spfh) session.commit() reged_spfh = session.query(SPFH).filter(SPFH.name == name).first() if not reged_spfh: abort(404, message="SPFH stock {} doesn't exist".format(name)) return reged_spfh
def update_news(): news = get_news(url="https://news.ycombinator.com/newest") make_news = [] for i in news: title, author = i["title"], i["author"] if not list( session.query(News).filter(News.title == title, News.author == author)): make_news.append(i) make_table_news(session, make_news) redirect("/news")
def save_similar_idcodes(idcode: str, pid: int, seqid: float = 0.9): exists_cluster = session.query(Similarity.pid).filter_by(pid=pid).first() if exists_cluster: logging.info(f"{idcode} similarity cluster already exists.") return similar = get_similar_idcodes(idcode, pid, seqid=seqid) if similar: new_cluster = Similarity(pid=pid, cluster=similar, seqid=seqid) session.add(new_cluster) session.commit()
def on_get(self, req, resp): try: userinfo = req.context['user'] if not userinfo.is_logged_in(): req.context['result'] = util.profile.fake_profile() return profile = session.query(model.Profile).get(userinfo.id) notify = session.query(model.UserNotify).get(userinfo.id) req.context['result'] = { 'basicProfile': util.profile.to_json( userinfo.user, profile, notify, req.context['year_obj'], basic=True )['profile'] } except SQLAlchemyError: session.rollback() raise finally: session.close()
def get_events(): if re.search('(?:iPhone|iPad|iPod)', request.user_agent.string): iOS = True else: iOS = False now = datetime.datetime.now(mountain) events = [] for event in session.query(Event).all(): if event.all_day: start = mountain.localize(event.start) end = mountain.localize(event.end) else: start = utc.localize(event.start).astimezone(mountain) end = utc.localize(event.end).astimezone(mountain) if now > end: continue event.date = start.strftime('%a %b %d') event.time = start.strftime('%I:%M %p') + " - " + end.strftime('%I:%M %p') data = {} data['action'] = 'TEMPLATE' data['hl'] = 'en' data['ctz'] = 'America/Denver' data['text'] = 'Josh Blackburn at {}'.format(event.title) if event.location: data['location'] = event.location event.gmap_link = "//maps.google.com/maps?q={}".format(quote_plus(event.location)) event.imap_link = "//maps.apple.com/?q={}".format(quote_plus(event.location)) else: data['location'] = event.title event.gmap_link = None event.imap_link = None if event.all_day: data['dates'] = start.strftime('%Y%m%d') + '/' + end.strftime('%Y%m%d') else: data['dates'] = start.strftime('%Y%m%dT%H%M%S') + '/' + end.strftime('%Y%m%dT%H%M%S') event.gcal_link = 'https://calendar.google.com/calendar/event?{}'.format(urlencode(data)) c = iCal() e = iEvent() e.name = data['text'] e.begin = start e.end = end e.location = data['location'] c.events.add(e) event.ics_link = "data:text/calendar,{}".format(quote(str(c))) if iOS: event.cal_link = event.ics_link event.map_link = event.imap_link else: event.cal_link = event.gcal_link event.map_link = event.gmap_link events.append(event) session.close() return events
def populate_db(): categories = json.loads(fetch_data()) for category in categories: for key in category: db_category = session.query(Category).filter( Category.name == key).first() if not db_category: db_category = Category(name=key) session.add(db_category) session.commit() print(db_category) for book in category[key]: db_book = session.query(Book).filter( Book.title == book.get("title")).first() if not db_book: db_book = Book(title=book.get("title"), link=book.get("link"), category_id=db_category.id) session.add(db_book) session.commit() print(db_book)
def upload_fb(): body = request.get_json() token = body.get('token') files = body.get('files') i = 0 try: idinfo = id_token.verify_oauth2_token(token, requests.Request(), environ.get("GOOGLE_CLIENT_ID")) if idinfo['iss'] not in [ 'accounts.google.com', 'https://accounts.google.com' ]: raise ValueError('Wrong issuer') userid = idinfo['sub'] try: user = session.query(User).filter(User.id == userid).one() except: user = User(id=userid) session.add(user) session.commit() for text in files: try: new_thread = MessageThread(id=i, user_id=user.id, person=str(i)) session.add(new_thread) i += 1 try: session.commit() except: session.rollback() p, msgs = scrapePage( str(i), text.replace(' EDT', '').replace(' EST', '')) for m in msgs: date = datetime.fromtimestamp(m['date']) msg = Message(thread_id=new_thread.id, type='FB', body=m['body'], date=date, user_speaking=m['user_speaking']) session.add(msg) except Exception as e: return str(e) try: session.commit() except: session.rollback() return 'Error', 401 return json.dumps({'msg': 'Success'}), 200 except Exception as e: session.rollback() return str(e)
def verify_auth_token(token): s = Serializer(SECRET_KEY) try: print(token) data = s.loads(token) except SignatureExpired: return None # valid token, but expired except BadSignature: return None # invalid token user = session.query(User).filter(User.id == data['id']).first() print("Verified with auth token") return user
def delete_ads_for_search(self, search, user_id): query = session.query(All_ads).filter( and_( All_ads.search == search, All_ads.user_id == user_id, All_ads.show == 1 ) ) query.all() for ad in query: session.delete(ad) session.commit()
def is_spam(message: Message) -> bool: """ Returns True/False if the message is too soon to be reacted to with a gif :param message: The Message object from Discord :return: bool: Is the message too soon to respond to prevent spam """ db_query = session.query(MessageHistory).filter_by(guild_id=message.guild.id, channel_id=message.channel.id) if message_history := db_query.first(): # if now < 2 hours ago + 6 hour wait time # Too Soon, don't spam if datetime.now() < message_history.last_posted + anti_spam_wait_time: return True
def verify_password(username_or_token, password): # first try to authenticate by token user = User.verify_auth_token(username_or_token) if not user: # try to authenticate with username/password user = session.query(User).filter_by(username=username_or_token).first() if not user or not user.verify_password(password): return False g.user = user return True
def get(self): args = parser.parse_args() name = args['name'] if name is None: abort(400, message="Couldn't find the name") spfh = session.query(SPFH).filter_by(name=name).first() if spfh is None: abort(404, message="stock {} does not exist".format(name)) return spfh
async def show_progress_task(msg: Message, state: FSMContext): user_id = msg.from_user.id tasks = session.query(Tasks).filter(Tasks.user_id == user_id, Tasks.progress == 'in_progress').all() await msg.answer(text=f'Кличество: {len(tasks)}', reply_markup=panel_exit) for i, task in enumerate(tasks): panel = inline_progress_task(task.id) await msg.answer(text=f'Номер: {i + 1}\n' f'Название: {task.title}', reply_markup=panel) await SubordinateRoleState.ProgressTask.set()
def add_item(): title = request.GET.get('title') price = request.GET.get('price') desc = request.GET.get('desc') lng = request.GET.get('lng') lat = request.GET.get('lat') item = Item(title=title, price=price, desc=desc) user = session.query(User).filter_by(name='jimmy').first() user.itemlist.append(item) session.commit() return "user %s added!" % title
def put(self, review_id): parsed_args = parser.parse_args() review = session.query(Review).filter( Review.review_id == review_id).first() review.review_id = parsed_args['review_id'] review.username = parsed_args['username'] review.rating = parsed_args['rating'] review.review = parsed_args['review'] review.dish_id = parsed_args['dish_id'] session.add(review) session.commit() return review, 201
def delete(self): args = parser.parse_args() name = args['name'] if name is None: abort(400, message="Couldn't find the name") spfh = session.query(SPFH).filter_by(name=name).first() if spfh is None: abort(404, message="stock {} does not exist".format(name)) try: num_rows_deleted = session.query(SPFH).filter_by( name=name).delete() session.commit() return { "message": "{} number of row(s) deleted.".format(num_rows_deleted) } except: session.rollback()
def delete_todo(id: int): todo = session.query(TodosTable).\ filter(TodosTable.id == id).first() try: session.delete(todo) session.commit() except: session.rollback() raise return {}
def delete(self, id): l = session.query(LawyerModel).filter(LawyerModel.id == id).first() if l: session.delete(l) session.commit() return {}, 204 else: return abort(404, message="Lawyer with the id " + str(id) + " doesn't exist.")
async def done_task(call: CallbackQuery, callback_data: dict, state: FSMContext): await call.message.delete() task_id = callback_data['info'] task = session.query(Tasks).get(task_id) task.progress = 'done' session.commit() user = task.user chief_id = user.chief.user_id await bot.send_message(chat_id=chief_id, text=f'Подчиненный: {user.name} выполнил задание\n' f'Название: {task.title}', reply_markup=inline_show_file_to_task(task_id))
def save_log(message, created_at, user_id): """Сохранение лога в БД""" logs_exists = session.query(Log).filter( created_at == Log.created_at).count() if not logs_exists: new_log = Log(message=message, created_at=created_at, user_id=int(user_id)) session.add(new_log) session.commit() logger.debug( f'Лог созданный в {created_at} пользователем {user_id} сохранен!')
def save_structure_quality(idcode, pid): """ https://data.rcsb.org/rest/v1/core/entry/4LZT ls_rfactor_rfree clashscore percent_ramachandran_outliers percent_rotamer_outliers percent_rsrzoutliers """ exists_validation = (session.query( StructureValidation.pid).filter(StructureValidation.pid == pid).all()) if exists_validation: logging.info(f"{idcode} structure validation already exist.") return r = requests.get(f"https://data.rcsb.org/rest/v1/core/entry/{idcode}") if not r.ok: logging.error( f"Unable to get structure validation info about {idcode}") return content = r.json() rfree = None clashscore = None percent_ramachandran_outliers = None percent_rotamer_outliers = None percent_rsrzoutliers = None if "refine" in content and "ls_rfactor_rfree" in content["refine"][0]: rfree = content["refine"][0]["ls_rfactor_rfree"] if "pdbx_vrpt_summary" in content: val_summ = content["pdbx_vrpt_summary"] if "clashscore" in val_summ: clashscore = val_summ["clashscore"] if "percent_ramachandran_outliers" in val_summ: percent_ramachandran_outliers = val_summ[ "percent_ramachandran_outliers"] if "percent_rotamer_outliers" in val_summ: percent_rotamer_outliers = val_summ["percent_rotamer_outliers"] if "percent_rsrzoutliers" in val_summ: percent_rsrzoutliers = val_summ["percent_rsrzoutliers"] new_val = StructureValidation( pid=pid, rfree=rfree, clashscore=clashscore, rama=percent_ramachandran_outliers, rota=percent_rotamer_outliers, rsrz=percent_rsrzoutliers, ) session.add(new_val) session.commit()
def delete(self, account_id): account = session.query(FacultyModel).filter( FacultyModel.id == account_id).first() if not account: abort(404, message="Account with the id {} was not found".format( account_id)) session.delete(account) session.commit() return {}, 204
def getTransactionDateStat(): results = session.query(func.extract('year', Order.transaction_date).cast(Integer).label('year'), func.count('year')) \ .group_by('year') \ .order_by('year').all() listed = list(zip(*results)) ts = pd.DataFrame(np.array(listed[1]), listed[0]) ts.plot(kind='bar', figsize=(9, 7), title="Sale statistics") plt.plot(ts) plt.show()
def checkPriorities(self, client_id, new_client_priority, new_title): # initializing priorities dictionary priorities_dict = {} # find all active feature requests (with date_finished = None) try: features_same_client = session.query(FeatureRequest).filter(FeatureRequest.client_id == client_id).filter(FeatureRequest.date_finished == None) # noqa except: session.rollback() print("Error in check priorities pt 2 - 1") # filling dictionary for feature_same_client in features_same_client: priorities_dict[str(feature_same_client.client_priority)] = feature_same_client.title # noqa # checking if priority number exists if str(new_client_priority) in priorities_dict: # get data of existing priority (removing the key) old_key = new_client_priority old_title = priorities_dict[str(old_key)] # while key exists continue incrementing by 1 while str(old_key) in priorities_dict: aux = int(old_key) aux = aux + 1 old_key = str(aux) del priorities_dict[str(new_client_priority)] # add new priority and title priorities_dict[str(new_client_priority)] = new_title # add old priority and title priorities_dict[str(old_key)] = old_title # get old Feature Request that matches the parameters try: feature_request = session.query(FeatureRequest).filter(FeatureRequest.title == old_title).filter(FeatureRequest.client_priority == new_client_priority).filter(FeatureRequest.client_id == client_id).first() # noqa except: session.rollback() print("Error in check prioritues pt 2 - 2") feature_request.client_priority = int(old_key) try: session.add(feature_request) session.commit() except: session.rollback()
def on_get(self, req, resp, id): try: user = req.context['user'] task = session.query(model.Task).get(id) if task is None: req.context['result'] = { 'errors': [{ 'status': '404', 'title': 'Not found', 'detail': 'Úloha s tímto ID neexistuje.' }] } resp.status = falcon.HTTP_404 return if ((not user.is_logged_in()) or ((not user.is_org()) and (not user.is_tester()))): if not session.query(model.Wave).get(task.wave).public: req.context['result'] = { 'errors': [{ 'status': '403', 'title': 'Forbidden', 'detail': 'Úloha s tímto ID je uzamčena.' }] } resp.status = falcon.HTTP_403 return req.context['result'] = { 'task': util.task.to_json(task, prereq_obj=task.prerequisite_obj, user=user) } except SQLAlchemyError: session.rollback() raise finally: session.close()
def post(self): data = request.get_json(); try: qry_transactions = session.query(TransactionsTbl).join(TransactionsTbl.status).order_by(TransactionsTbl.id.asc()).all() list_transactions = [] for transaction in qry_transactions: new_transaction = TransactionsTbl(status_id=1, date_created=now) session.add(new_transaction) session.flush() session.refresh(new_transaction) products = []; total = 0; for product in data['products']: qry_products = session.query(ProductsTbl).filter(ProductsTbl.id == product['id']).first() total += product['amount']*qry_products.price products.append(TransactionProducts(transaction_id=new_transaction.id, product_id=product['id'], amount=product['amount'])) new_stock = qry_products.stock - product['amount']; session.query(ProductsTbl).filter(ProductsTbl.id == product['id']).update({'stock': new_stock}) session.bulk_save_objects(products) session.query(TransactionsTbl).filter(TransactionsTbl.id == new_transaction.id).update({'total': float(total)}) session.commit() except (sqlalchemy.exc.SQLAlchemyError, sqlalchemy.exc.DBAPIError) as e: return dumps(e), 400 return dumps({}), 201
def delta(symbol: str) -> Dict[str, Any]: """Функция, возвращающая данные о минимальных периодах, когда цена изменилась больше, чем на N. :param symbol: название акции :return: словарь, содержащий данные о минимальных периодах, когда цена изменилась больше, чем на N """ canonical_symbol = canonize_symbol(symbol) if symbol != canonical_symbol: abort(redirect(url_for(request.endpoint, symbol=canonical_symbol, **request.args), 301)) ticker = session.query(Ticker).filter( Ticker.symbol == symbol ).first() if ticker is None: abort(404) value: Optional[float] try: value = float(request.args.get('value', '')) except ValueError: value = None value_type = request.args.get('type') if value_type not in types_enum: value_type = None if value is None or value_type is None: return { 'ticker': ticker.symbol, 'min_duration': None, 'type': value_type, 'value': value, } intervals = HistoricalPrice.get_intervals(ticker, value_type, value) return { 'ticker': ticker.symbol, 'min_duration': intervals[0][4] if intervals else None, 'type': value_type, 'delta': value, 'intervals': [ { 'date_from': interval[0].isoformat(), 'date_to': interval[1].isoformat(), 'delta': interval[2], } for interval in intervals ] }
def lyrics(): artist, title = map(request.args.get, ['artist', 'title']) if not artist: return request.error_formatter(10, 'Missing artist parameter') if not title: return request.error_formatter(10, 'Missing title parameter') query = session.query(Track).join(Album, Artist).filter( func.lower(Track.title) == title.lower() and func.lower(Artist.name) == artist.lower()) for track in query: lyrics_path = os.path.splitext(track.path)[0] + '.txt' if os.path.exists(lyrics_path): app.logger.debug('Found lyrics file: ' + lyrics_path) try: lyrics = read_file_as_unicode(lyrics_path) except UnicodeError: # Lyrics file couldn't be decoded. Rather than displaying an error, try with the potential next files or # return no lyrics. Log it anyway. app.logger.warn('Unsupported encoding for lyrics file ' + lyrics_path) continue return request.formatter({ 'lyrics': { 'artist': track.album.artist.name, 'title': track.title, '_value_': lyrics } }) try: r = requests.get( "http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect", params={ 'artist': artist, 'song': title }) root = ElementTree.fromstring(r.content) ns = {'cl': 'http://api.chartlyrics.com/'} return request.formatter({ 'lyrics': { 'artist': root.find('cl:LyricArtist', namespaces=ns).text, 'title': root.find('cl:LyricSong', namespaces=ns).text, '_value_': root.find('cl:Lyric', namespaces=ns).text } }) except requests.exceptions.RequestException, e: app.logger.warn('Error while requesting the ChartLyrics API: ' + str(e))
def checkUser(user, password): userinfo = session.query(UserInfo).filter_by(username=user).first() if not userinfo: return False password_db = userinfo.password password_encrypt = encrypt(user + password) if password_encrypt[0:20] == password_db: return True else: return False
def put(self, id: int) -> dict: ingredient = session.query(Ingredient).get(id) update_params = self.update_params() for key, value in update_params.items(): setattr(ingredient, key, value) session.commit() ingredient = IngredientClientSchema().dump(ingredient) response = BasicResponse(ingredient) return BasicResponseSchema().dump(response)