def register_post(): form = RegistrationForm(request.form) if form.validate(): user = session.query(User).filter_by(username=form.username.data).first() if user: flash('That username is already in use', 'danger') return redirect(url_for('register_get')) user = session.query(User).filter_by(email=form.email.data).first() if user: flash('That email is already in use', 'danger') return redirect(url_for('register_get')) newuser = User(username=form.username.data, email=form.email.data, password=generate_password_hash(form.password.data) ) if form.fname.data and form.lname.data: newuser.realname = form.fname.data + form.lname.data elif form.fname.data: newuser.realname = form.fname.data elif form.lname.data: newuser.realname = form.lname.data session.add(newuser) session.commit() flash('Thanks for registering!', 'success') return redirect(url_for('login_get')) else: flash_errors(form) return render_template('register.html', form=form)
def add_poi_post(): form = POIForm(request.form) if form.validate(): location = session.query(POI).filter_by(address=form.address.data).first() if location: flash('That location is already in the database!', 'warning') return redirect(url_for('add_poi_get')) lat, lng = geocode(form.address.data) if lat and lng: poi = POI(name=form.name.data, category=form.category.data, address=form.address.data, latitude=lat, longitude=lng, desc=form.desc.data) session.add(poi) session.commit() user = session.query(User).get(int(current_user.get_id())) user.poi_assocs.append(UserPOI(poi=poi, upvote=1)) session.commit() flash('You added a new place!', 'success') return redirect(url_for('index')) else: flash('Google Maps could not find that address. Try again!', 'warning') return render_template('add_poi.html', form=form) else: flash_errors(form) return render_template('add_poi.html', form=form)
def check(): data = request.form try: if data['username'] and data['password']: pass except KeyError: return message_('User and pass required.') query = session.query(Participant).\ filter(Participant.username == data['username']) try: participant = query.one() except NoResultFound: return message_('Not signed up.') if not sha256_crypt.verify(data['password'], participant.password): return message_('Password incorrect.') try: match = session.query(Participant).\ filter(Participant.id == participant.match_id).one() except NoResultFound: return message_('No match.') return match.username
def get(self): request = Category.parser.parse_args() return_list = [] if request['category_pk'] == None: category = session.query(models.Category).all() if category == None: # 데이터가 존재하지 않기 때문에 404 반환 return Response(status=404) # 데이터베이스 객체 딕셔너리로 파싱 작업 for i in category: return_list.append({ 'categoryPk': i.category_pk, 'categoryName': i.category_name }) else: try: category = session.query(models.Category).filter( models.Category.category_pk == request['pk']).first() # 데이터베이스 객체 딕셔너리로 파싱 작업 return_list.append({ 'categoryPk': category.category_pk, 'categoryName': category.category_name }) except: #filter함수에 반환 값이 없으면 오류 발생으로 404 반환 return Response(status=404) session.close() return {'data': return_list}, 200
def song_analysis_get(id): """ Get the analysis for a single song endpoint """ # Get the song from the database song = session.query(models.Song).get(id) # Check whether the song exists # If not return a 404 with a helpful message if not song: message = "Could not find song with id {}".format(id) data = json.dumps({"message": message}) return Response(data, 404, mimetype="application/json") # Get the filename files = session.query(models.File).all() file1id = files[song.column-1].id #file1name = session.query(models.File).get(filename) #songname = file[song.column].filename songname = files[file1id-1].filename analysis = analyse(songname) data = json.dumps(analysis) return Response(data, 200, mimetype="application/json")
def delete_meme_from_list(message): if message.reply_to_message: meme_subreddits = session.query(MemeSubreddit).filter( MemeSubreddit.user == message.from_user.id).all() try: meme_subreddit = message.reply_to_message.caption.split( "/r/")[1][:-1] if meme_subreddit in { subreddit.subreddit for subreddit in meme_subreddits }: (session.query(MemeSubreddit).filter( MemeSubreddit.user == message.from_user.id, MemeSubreddit.subreddit == meme_subreddit).delete()) session.commit() bot.send_message( message.chat.id, f"/r/{meme_subreddit} успешно удалён из списка!") else: bot.send_message(message.chat.id, f"/r/{meme_subreddit} не найден в списке!") except: bot.send_message( message.chat.id, "Что-то пошло не так!\nНе удалось обновить список!") else: bot.send_message(message.chat.id, "Отправь команду через Reply!")
def song_edit(id): song = session.query(models.Song).get(id) if not song: message = "Could not find song with id {}".format(id) data = json.dumps({"message": message}) return Response(data, 404, mimetype="application/json") song_file = session.query(models.File).filter_by(id=song.file_id).first() data = request.json song_file.filename = data["filename"] session.commit() """Print outs to veiw how data looks during execution above print("print outs from song_edit()") print("Orig son file data is {}".format(song.as_dictionary())) print("Orig file data is {}".format(song_file.as_dictionary())) print("data from test is showing as {}".format(data)) """ data = json.dumps(song.as_dictionary()) """Print out to see how data above looks print("song_edit() final response data") """ headers = {"Location": url_for("song_get", id=id)} return Response(data, 201, headers=headers, mimetype="application/json")
def top_ten(): result = session.query(POI.id, POI.category, POI.name, func.sum(UserPOI.upvote) ).join(UserPOI).group_by(POI.id).order_by(POI.id) # Add in User info, if applicable user_visited = [] if not current_user.is_anonymous(): user = session.query(User).get(int(current_user.get_id())) for assoc in user.poi_assocs: user_visited.append(assoc.poi_id) poi_list = [] for row in result: entry = { "id": row[0], "category": row[1], "name": row[2], "total_upvotes": row[3], "visited": row[0] in user_visited } poi_list.append(entry) # Sort and return the Top Ten top_ten = sorted(poi_list, key=lambda k: k['total_upvotes'], reverse=True)[:10] return render_template('top_ten.html', top_ten=top_ten)
async def handle_unsubscribe(bot, ctx, sub_arg): if len(sub_arg) == 0: return await bot.send(ctx, '缺少参数') if is_number(sub_arg[0]) == False and sub_arg[0] != 'all': return await bot.send(ctx, message='参数只能是编号或者all', at_sender=True) user_id = ctx['user_id'] try: if sub_arg[0] == 'all': session.query(UserSubscribe).filter( UserSubscribe.user_id == user_id).delete() else: if is_number(sub_arg[0]) == False: return await bot.send(ctx, message='参数只能是编号或者all', at_sender=True) session.query(UserSubscribe).filter( and_(UserSubscribe.user_id == user_id, UserSubscribe.vid == sub_arg[0])).delete() except Exception: session.rollback() return await bot.send(ctx, message='成功取消订阅(如未订阅请忽略)', at_sender=True)
def wrapper(*args, **kwds): category_name = kwds["category_name"] item_title = kwds["item_title"] # Redirect user if category or item does not exist. category = session.query(Category).filter_by( name=category_name).one_or_none() if not category: flash("An error occurred. Please try again.", "warning") return redirect("/catalog") item = session.query(Item).filter_by( category_id=category.id, title=item_title).one_or_none() if not item: flash("An error occurred. Please try again.", "warning") return redirect("/catalog/{}/items".format(category_name)) # Make sure the user owns an item before allowing them to edit # or delete it. if "username" not in login_session\ or "user_id" in login_session\ and item.user_id != login_session["user_id"]: flash("You are not allowed to edit or delete this item. " "It belongs to {}.".format(item.user.name), "warning") return render_template("show_item.html", item=item) kwds['item'] = item return f(*args, **kwds)
def delete_patient(id): patient = session.query(Patient).filter(Patient.id == id).all() name = patient[0].name session.query(Patient).filter(Patient.id == id).delete() database.session.commit() flash("Successfully deleted patient {}".format(name)) return redirect(url_for('index'))
def delete_reminder(id, reminder_id, search_id): reminder = session.query(Reminder).filter( Reminder.id == reminder_id).first() flash("Deleted reminder") # forall reminders, we'll need to delete them from the db (ez pz) # if its a 'single reminder', we just kill the at job (ez) # if its a 'recurring reminder' we need to: # remove the cron job # remove the at job (if it exists) (this is when it has an end_on value) # delete the appropriate .scheduling/ files (if they exist, i.e. when it has an end_after value) if reminder.at_id is not None: proc = subprocess.Popen(['atrm', str(reminder.at_id)]) if reminder.extra_at_id is not None: proc = subprocess.Popen(['atrm', str(reminder.extra_at_id)]) if reminder.reminder_type == 2: # recurring reminder proc = subprocess.Popen(["bash"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) proc.stdin.write("crontab -l | grep -Fv \"{}\" | crontab - ".format( reminder.cron_command)) proc.stdin.close() if reminder.sched_file_prefix is not None and reminder.sched_file_prefix != "": proc = subprocess.Popen( ["rm", "{}*".format(reminder.sched_file_prefix)]) session.query(Reminder).filter(Reminder.id == reminder_id).delete() session.commit() return redirect(url_for('view_reminders', id=id, serach_id=search_id))
def __repr__(self): shiftcategory = session.query(ShiftCategory).filter( ShiftCategory.id == self.shift_category_id).one_or_none() company = session.query(Company).filter( Company.id == shiftcategory.company_id).one_or_none() return '{}({})({})'.format(self.name, shiftcategory.name, company.code)
def get(): user = session.query(User).filter( User.code == api_basic_auth.username()).one_or_none() if user is None: session.close() frame = inspect.currentframe() abort(404, { 'code': frame.f_lineno, 'msg': '指定されたユーザは存在しません', 'param': None }) salary_tables_results = session.query(Salary, ShiftTable)\ .join(ShiftTable)\ .filter(Salary.user_id == user.id)\ .order_by(Salary.created_at.asc())\ .all() results = [] for salary, table in salary_tables_results: results.append({'pay': salary.pay, 'title': table.title}) session.close() return jsonify({'results': results}), 200
def delete_restaurant(restaurant_id): try: restaurant_to_delete = session.query(Restaurant).filter_by( id=restaurant_id).one() except: return "No such restaurant to delete" if restaurant_to_delete.user_id != login_session['user_id']: return "<script>function myFunction() {" \ "alert('You are not authorized to delete this restaurant. " \ "Please create your own restaurant in order to delete.');}" \ "</script><body onload='myFunction()''>" if request.method == 'POST': session.delete(restaurant_to_delete) menu_items_to_delete = session.query(MenuItem).filter_by( restaurant_id=restaurant_id).all() for del_menu in menu_items_to_delete: session.delete(del_menu) flash('%s Successfully Deleted' % restaurant_to_delete.name) session.commit() return redirect( url_for('restaurant.show_restaurants', restaurant_id=restaurant_id)) else: return render_template('deleteRestaurant.html', restaurant=restaurant_to_delete)
def save_to_database(data): try: user = session.query(User).filter_by(id=str(data["user"]["id"])).one() except NoResultFound: user = create_user_helper(data["user"]) session.add(user) hashtag_results = [] hashtags = data["entities"]["hashtags"] for hashtag in hashtags: hashtag = hashtag["text"].lower() try: hashtag_obj = session.query(Hashtag).filer_by(text=hashtag).one() except NoResutlFound: user = create_ hashtag_obj = Hashtag(text=hashtag) session.add(hashtag_obj) hashtag_results.append(hashtag_obj) tweet = create_tweet_helper(data, user) for hashtag in hashtag_results: tweet.hashtags.append(hashtag) session.add(tweet) session.commit()
def getNumberFromAlias(self, alias): if session.query(exists().where(Recipients.alias == alias)).scalar(): return session.query(Recipients).filter(Recipients.alias == alias).first().phoneNumber elif session.query(exists().where(Recipients.phoneNumber == alias)).scalar(): return alias else: raise 'Unknown alias in getNumberFromAlias'
def edit_menu_item(restaurant_id, menu_id): try: edited_item = session.query(MenuItem).filter_by(id=menu_id).one() except: return "No such item" try: restaurant = session.query(Restaurant).filter_by( id=restaurant_id).one() except: return "No such restaurant" if login_session['user_id'] != restaurant.user_id: return "<script>function myFunction() {" \ "alert('You are not authorized to edit menu items" \ " to this restaurant. " \ "Please create your own restaurant in order " \ "to edit items.');}" \ "</script><body onload='myFunction()''>" if request.method == 'POST': for (key, value) in request.form.items(): setattr(edited_item, key, value) session.add(edited_item) session.commit() flash('Menu Item Successfully Edited') return redirect( url_for('menu_item.show_menu', restaurant_id=restaurant_id)) else: return render_template('editmenuitem.html', restaurant_id=restaurant_id, menu_id=menu_id, item=edited_item)
def song_delete(): """ delete a song """ headers = {"Location": url_for("song_delete")} # get the data from the form data = request.json post_song = models.Song(song_name=data["song_name"],id=data["song_id"]) ## ask sam if we really need to post seperately. post_file = models.File(song_id=data["song_id"],file_name=data["file_name"],id=data["file_id"]) if session.query(models.Song).get(post_song.id): #consider adding a check here for duplicate fileID too del_song=session.query(models.Song).get(post_song.id) session.delete(del_song) del_file = session.query(models.File).get(post_file.id) session.delete(del_file) session.commit() else: print "************* ELSE ***************" session.rollback() session.flush() return Response(json.dumps({"status":"failed - that song doesnt exists"}),500,mimetype="application/json") return Response(json.dumps({"status":"deleted"}), 200, headers=headers, mimetype="application/json")
def get(): admin_user = session.query(User).filter( User.code == api_basic_auth.username()).one() if admin_user.role.name != 'admin': session.close() frame = inspect.currentframe() abort(403, {'code': frame.f_lineno, 'msg': '権限がありません', 'param': None}) users_role = session.query(User, Role).join(Role).filter( User.company_id == admin_user.company_id).order_by( User.order.asc()).all() company = session.query(Company).filter( Company.id == admin_user.company_id).one() users = [] for user, role in users_role: users.append({ 'name': user.name, 'code': user.code, 'order': user.order, 'role': role.name, 'password': '******' if user.is_authed else user.password }) session.close() return jsonify({'results': {'users': users, 'company': company.code}}), 200
def getNumberFromAlias(self, alias): if session.query(exists().where(Recipients.alias == alias)).scalar(): return session.query(Recipients).filter(Recipients.alias == alias).first().phoneNumber elif session.query(exists().where(Recipients.phoneNumber == alias)).scalar(): return alias else: raise "Unknown alias in getNumberFromAlias"
def get(self, page=1): """Retrieve all bucketlists belonging to the logged in user. limit specifies the maximum number of results per page specified with default set to 20. q specifies the term to search by through the bucketlists """ try: limit = int(request.args['limit']) except BadRequestKeyError: limit = 20 if limit > 100: limit = 100 q = request.args.get('q', type=str) created_by = current_user.user_id if created_by: if q: bucketlistget = session.query(BucketList).filter_by( creator=created_by).filter( BucketList.list_name.contains(q)) else: bucketlistget = session.query(BucketList).filter_by( creator=created_by) paginate = Paginator(bucketlistget, limit) page_responses = paging(bucketlists, paginate, page) return page_responses return {'message': 'Please login to view your bucketlists'}, 401
def confirm_tg_account(bot, update, user_data): code = update.message.text tg_session = session.query(TelegramSession).filter( TelegramSession.id == int(user_data['session_id'])).first() user = session.query(User).filter( User.tg_id == update.message.chat_id).first() client = TelegramClient( os.path.join(config.TELETHON_SESSIONS_DIR, tg_session.phone_number), user.api_id if user.api_id else config.TELEGRAM_API_ID, user.api_hash if user.api_hash else config.TELEGRAM_API_HASH) client.connect() try: client.sign_in(tg_session.phone_number, code, phone_code_hash=tg_session.phone_code_hash) tg_session.active = True update.message.reply_text('Account added successfully.') except Exception as e: update.message.reply_text('Error: {}.'.format(e)) path = os.path.join(config.TELETHON_SESSIONS_DIR, '{}.session'.format(tg_session.phone_number)) if os.path.exists(path): os.remove(path) session.delete(tg_session) session.commit() client.disconnect() return ConversationHandler.END
def posts(page=1, paginate_by=10): # Zero-indexed page page_index = page - 1 count = session.query(Post).count() start = page_index * paginate_by # The index of the first item that we should see end = start + paginate_by # The index of the last item that we should see total_pages = (count - 1) / paginate_by + 1 # The total number of pages of content has_next = page_index < total_pages - 1 # Whether there is a page after our current one has_prev = page_index > 0 # Whether there is a page before our current one posts = session.query(Post) posts = posts.order_by(Post.datetime.desc()) posts = posts[start:end] return render_template("posts.html", posts=posts, has_next=has_next, has_prev=has_prev, page=page, total_pages=total_pages, )
def __init__(self, parent=0, *args, **kwargs): QtGui.QWidget.__init__(self, parent, *args, **kwargs) self.setWindowTitle(_(u"Choice of type and period")) #Title widget title = QtGui.QLabel() title.setText(_(u"Choose a account and a period")) title.setAlignment(QtCore.Qt.AlignHCenter) title_hbox = QtGui.QHBoxLayout() title_hbox.addWidget(title) #Combobox widget self.box_account = QtGui.QComboBox() self.box_period = QtGui.QComboBox() self.box_type = QtGui.QComboBox() # Data self.all_active_periods = all_active_periods(session.query(Period).\ order_by(desc(Period.start_on)).all()) self.data_account = session.query(Account).all() self.box_account.addItem(_(u"All Accounts")) for index in xrange(0, len(self.data_account)): account = self.data_account[index] self.box_account.addItem(_(u'%(number)s %(name)s') %\ {'number': account.number, 'name': account.name}) sel_index = 0 for index in xrange(0, len(self.all_active_periods)): ped = self.all_active_periods[index] if ped == current_period(): sel_index = index self.box_period.addItem(_(u'%(display_name)s') %\ {'display_name': ped.display_name()}) self.box_period.setCurrentIndex(sel_index) #Ok and cancel hbox button_hbox = QtGui.QHBoxLayout() #Ok Button widget. operation_but = QtGui.QPushButton(_("list of operations per account")) button_hbox.addWidget(operation_but) operation_but.clicked.connect(self.Operation_pdf) #Cancel Button widget. balance_but = QtGui.QPushButton(_("Balances (All accounts)")) button_hbox.addWidget(balance_but) balance_but.clicked.connect(self.balance_pdf) combo_hbox = QtGui.QHBoxLayout() combo_hbox.addWidget(self.box_account) combo_hbox.addWidget(self.box_period) vbox = QtGui.QVBoxLayout() vbox.addLayout(title_hbox) vbox.addLayout(combo_hbox) vbox.addLayout(button_hbox) self.setLayout(vbox)
def get(self): request = Menu.parser.parse_args() return_list = [] if request['pk'] == None: menus = session.query(models.Menu).all() if menus == None: return Response(status=404) for menu in menus: return_list.append({ 'menuPk': menu.menu_pk, 'categoryPk': menu.category_pk, 'menuName': menu.menu_name, 'menuPrice': menu.menu_price, 'menuSoldout': menu.menu_soldout, 'menuDescription': menu.menu_description, 'menuImage': menu.menu_image }) else: try: menu = session.query(models.Menu).filter( models.Menu.menu_pk == request['pk']).first() return_list.append({ 'menuPk': menu.menu_pk, 'categoryPk': menu.category_pk, 'menuName': menu.menu_name, 'menuPrice': menu.menu_price, 'menuSoldout': menu.menu_soldout, 'menuDescription': menu.menu_description, 'menuImage': menu.menu_image }) except: return Response(status=404) return {'data': return_list}, 200
def get_export_init(): access_user = session.query(User).filter(User.code == api_basic_auth.username()).one() company_users = session.query(User).filter( User.company_id == access_user.company_id ).all() follow = session.query(Follow, User) \ .join(User, Follow.follow_id == User.id) \ .filter(Follow.user_id == access_user.id) \ .one_or_none() if follow: follow_user = {'id': follow[1].id, 'name': follow[1].name} else: follow_user = None company_tables = session.query(ShiftTable).filter(ShiftTable.company_id == access_user.company_id).all() session.close() return jsonify({ 'me': {'id': access_user.id, 'name': access_user.name}, 'follow': follow_user, 'users': [{'name': user.name, 'id': user.id} for user in company_users], 'tables': [{'id': table.id, 'title': table.title} for table in company_tables] }), 200
def match_node(self, s, **kwargs): suggest = {'nodes': []} for res in session.query(Gene).filter(Gene.gene_id == s): print("There there") temp = { 'name': res.Symbol, 'gene_id': res.gene_id, 'info': res.description, 'tax_id': res.tax_id, 'equal': res.Symbol == s } suggest['nodes'].append(temp) return suggest for res in session.query(Gene).filter( Gene.Symbol.like(s + '%')).limit(100): temp = { 'name': res.Symbol, 'gene_id': res.gene_id, 'info': res.description, 'tax_id': res.tax_id, 'equal': res.Symbol == s } suggest['nodes'].append(temp) sorted(suggest['nodes'], key=lambda x: x['equal'], reverse=True) return suggest
def put(table): try: model = get_model_by_tablename(table) data = request.get_json() idx = data['index'] obj = session.query(model).get(idx) # неизмененное состояние строки note = '' flag = False for k in data.keys(): if data[k] != obj.__dict__[k] and data[k] != 'None': flag = True changed_row = '<{}>: "{}" -> "{}".'.format(k, obj.__dict__[k], data[k]) note += changed_row if flag: session.query(model).filter_by(index=idx).update(data) last_idx = len(session.query(History).all()) hist = History(index=last_idx, table=table, obj_id=int(idx), note=note) session.add(hist) res = make_response(jsonify({"message": "OK"}), 200) logger.info('Data changed in "{}" table. Object by index: {}'.format(table, idx)) return res except Exception as e: logger.error('Error occurred. Details: {}'.format(e)) abort(500)
def posts(page=1, paginate_by=10): # Zero-indexed page page_index = page - 1 count = session.query(Post).count() start = page_index * paginate_by end = start + paginate_by total_pages = (count - 1) / paginate_by + 1 has_next = page_index < total_pages - 1 has_prev = page_index > 0 posts = session.query(Post) posts = posts.order_by(Post.datetime.asc()) posts = posts[start:end] return render_template( "posts.html", posts=posts, has_next=has_next, has_prev=has_prev, page=page, total_pages=total_pages )
def get(self): request = Option.parser.parse_args() return_list = [] if request['pk'] == None: option = session.query(models.Option).all() session.close() # 데이터가 존재하지 않기 때문에 404 반환 if option == None: return Response(status=404) # 데이터베이스 객체 딕셔너리로 파싱 작업 for i in option: return_list.append({ 'optionPK': i.option_pk, 'optionName': i.option_name, 'optionPrice': i.option_price, 'optionSoldout': i.option_soldout }) else: try: option = session.query(models.Option).filter( models.Option.option_pk == request['pk']).first() session.close() # 데이터베이스 객체 딕셔너리로 파싱 작업 return_list.append({ 'optionPK': option.option_pk, 'optionName': option.option_name, 'optionPrice': option.option_price, 'optionSoldout': option.option_soldout }) except: # 해당 pk값을 가진 데이터가 존재하지 않기 때문에 404 반환 return Response(status=404) return {'data': return_list}, 200
def get_todays_mwe(language: str) -> Mwe: if language == "en": mwe: Mwe = session.query(Mwe).filter(Mwe.name == "give up").first() if mwe is None: mwe = Mwe(name="give up", meaning="cease making an effort; admit defeat", language="en") session.add(mwe) session.commit() return mwe else: return mwe elif language == "tr": mwe: Mwe = session.query(Mwe).filter( Mwe.name == "ayvayı yemek").first() if mwe is None: mwe = Mwe(name="ayvayı yemek", meaning="kötü bir duruma düşmek", language="tr") session.add(mwe) session.commit() return mwe else: return mwe
def add_account(bot, update, args, user_data): if len(args) == 1: phone_number = args[0] user = session.query(User).filter( User.tg_id == update.message.chat_id).first() tg_sessions = session.query(TelegramSession).filter( TelegramSession.user == user).all() phone_numbers = [s.phone_number for s in tg_sessions] if phone_number in phone_numbers: update.message.reply_text( "Sorry, this phone number already exists.") return ConversationHandler.END client = TelegramClient( os.path.join(config.TELETHON_SESSIONS_DIR, phone_number), user.api_id if user.api_id else config.TELEGRAM_API_ID, user.api_hash if user.api_hash else config.TELEGRAM_API_HASH) client.connect() result = client.send_code_request(phone_number, force_sms=True) client.disconnect() tg_session = TelegramSession(phone_number=phone_number, phone_code_hash=result.phone_code_hash, user=user) session.add(tg_session) session.commit() user_data['session_id'] = tg_session.id update.message.reply_text("Please, send the login code to continue") return LOGIN_CODE else: update.message.reply_text("Please, include the phone number to this " "command.") return ConversationHandler.END
def save_to_database(data): try: user = session.query(User).filter_by(id=str(data['user']['id'])).one() except NoResultFound: user = create_user_helper(data['user']) session.add(user) hashtag_results = [] hashtags = data['entities']['hashtags'] for hashtag in hashtags: hashtag = hashtag['text'].lower() try: hashtag_obj = session.query(Hashtag).filter_by(text=hashtag).one() except NoResultFound: hashtag_obj = Hashtag(text=hashtag) session.add(hashtag_obj) hashtag_results.append(hashtag_obj) tweet = create_tweet_helper(data, user) for hashtag in hashtag_results: tweet.hashtags.append(hashtag) session.add(tweet) session.commit()
def check_prices(): users = session.query(User).all() scrapper = Scrapper() items = session.query(Item).all() for item in items: scrapper.go_to(item.link) price = scrapper.get_price() title = scrapper.get_title() if not item.title: item.title = title session.commit() if item.price: change_percentage = (abs(price - item.price) / item.price) * 100.0 if change_percentage >= 3: item.price = price session.commit() markup = InlineKeyboardMarkup( [InlineKeyboardButton('Check', url=item.link)]) for u in users: try: bot.send_message( u.tg_id, '<code>{}</code> price changed'.format(title), parse_mode=ParseMode.HTML, reply_markup=markup) except Exception as e: config.logger.error( 'Error sending a message: {}'.format(e)) else: item.price = price session.commit()
def callback_inline(call): user = session.query(User).filter_by(user_id=call.message.chat.id).first() if not call.message: bot.delete_message(call.message.chat.id, call.message.message_id) user.state = 'main_menu_state' session.commit() get_state_and_process(call.message, user, True) if call.data == "save_categories": user.state = 'set_city_state' session.commit() get_state_and_process(call.message, user, True) else: subscription = session.query(UserSubscription).filter_by(name=call.data.replace("_on", ""), user_id=user.id).first() if not subscription: subscription = UserSubscription(name=call.data.replace("_on", ""), user_id=user.id) session.add(subscription) else: session.delete(subscription) session.commit() bot.edit_message_reply_markup( call.message.chat.id, call.message.message_id, call.message.message_id, reply_markup=categories_inline_keyboard(user=user) )
def get(): user = session.query(User).filter( User.code == api_basic_auth.username()).one() category_results = session.query(ShiftCategory).filter( ShiftCategory.company_id == user.company_id).all() scheme_results = session.query(ColorScheme).filter( ColorScheme.user_id == user.id).all() results = [] for category in category_results: scheme_category_match_result = [ x for x in scheme_results if x.shift_category_id == category.id ] tmp = {'category_id': category.id, 'category_name': category.name} if len(scheme_category_match_result) == 0: tmp['hex'] = None tmp['color_scheme_id'] = None else: tmp['hex'] = scheme_category_match_result[0].hex tmp['color_scheme_id'] = scheme_category_match_result[0].id results.append(tmp) session.close() return jsonify({'results': results}), 200
def select_task(bot, update, user_data): query = update.callback_query if query.data.startswith('tasks_next_page') or \ query.data.startswith('tasks_prev_page'): active_tasks = session.query(Task).all() buttons = [ InlineKeyboardButton(f'Inviting to {t.target_group}', callback_data=t.id) for t in active_tasks ] buttons = [buttons[i:i + 6] for i in range(0, len(buttons), 6)] if query.data.startswith('tasks_next_page'): go_to_page = int(query.data.split(':')[1]) else: go_to_page = int(query.data.split(':')[1]) if go_to_page > 0: prev_page_btn = InlineKeyboardButton( '⬅️', callback_data='tasks_prev_page:{}'.format(go_to_page - 1)) buttons[go_to_page].append(prev_page_btn) if go_to_page < len(buttons) - 1: next_page_btn = InlineKeyboardButton( '➡️', callback_data='tasks_next_page:{}'.format(go_to_page + 1)) buttons[go_to_page].append(next_page_btn) reply_markup = InlineKeyboardMarkup( build_menu(buttons[go_to_page], n_cols=2)) bot.edit_message_reply_markup(chat_id=query.message.chat_id, message_id=query.message.message_id, reply_markup=reply_markup, timeout=30) return SELECT_TASK else: task = session.query(Task).filter(Task.id == int(query.data)).first() user_data['task_id'] = task.id edit_interval_btn = InlineKeyboardButton('Edit interval', callback_data='edit_interval') delete_task_btn = InlineKeyboardButton('Delete task', callback_data='delete_task') buttons = [edit_interval_btn, delete_task_btn] reply_markup = InlineKeyboardMarkup(build_menu(buttons, n_cols=2)) text = f'Inviting to {task.target_group}\n' \ f'Source group: {task.source_group}\n' \ f'Accounts used: {len(task.accounts)}\n' \ f'Interval: every {task.interval} minutes\n' \ f'Last invite: {task.last_invite} \n' \ f'Please, choose action or /cancel' bot.edit_message_text(chat_id=query.message.chat_id, message_id=query.message.message_id, text=text, reply_markup=reply_markup, timeout=30) return TASK_MENU
def get_search_init(): access_user = session.query(User).filter( User.code == api_basic_auth.username()).one() shift_categories = session.query(ShiftCategory).filter( ShiftCategory.company_id == access_user.company_id).all() shifts = session.query(Shift).join(ShiftCategory).filter( ShiftCategory.company_id == access_user.company_id).all() users = session.query(User).filter( User.company_id == access_user.company_id).all() tables = session.query(ShiftTable).filter( ShiftTable.company_id == access_user.company_id).all() session.close() return jsonify({ 'results': { 'category': [{ 'id': category.id, 'name': category.name } for category in shift_categories], 'shift': [{ 'id': shift.id, 'name': shift.name } for shift in shifts], 'user': [{ 'id': user.id, 'name': user.name } for user in users], 'table': [{ 'id': table.id, 'title': table.title } for table in tables] } }), 200
def editItem(item_id): """Render a page that displays an HTML form to edit an item Renders a page with an HTML form that allows the owner of the item to edit and update the item details. """ formList = session.query(Medium).all() editedItem = session.query(ArtItem).filter_by(id=item_id).one() if request.method == 'POST': if request.form['name']: editedItem.name = request.form['name'] if request.form['description']: editedItem.description = request.form['description'] if request.form['material']: editedItem.material = request.form['material'] if request.form['image_url']: editItem.image_url = request.form['image_url'] if request.form['video_url']: editItem.video_url = request.form['video_url'] if request.form['year']: editedItem.year = request.form['year'] session.add(editedItem) session.commit() return redirect(url_for('showForms')) else: return render_template( 'edit-item.html', item=editedItem, media=formList, userinfo=login_session )
def view_post(post_id): posts = session.query(Post) count = session.query(Post).count() if post_id < 1 or post_id > count: return render_template("not_found.html") else: selected_post = posts.filter_by(id = post_id).first() return render_template("post_view.html", post = selected_post,)
def edit_post(postid): title = request.form["title"] content = mistune.markdown(request.form["content"]) session.query(Post).filter_by(id=postid).update({"title": title, "content": content}) session.commit() return redirect(url_for("posts"))
def setConfigOption(param, value): if type(value) == str: value = value.encode() if session.query(exists().where(Config.param == param)).scalar(): confobj = session.query(Config).filter(Config.param == param).first() confobj.value = value else: session.add(Config(param, value)) session.commit()
def get_media(media_id): user = session.query(User).filter_by(api_key=request.headers['X-Auth-Token']).first() media_file = session.query(Mp4Info).filter_by(id=media_id).first() if user: response = make_response(media_file.location) response.headers["Content-Disposition"] = "attachment; " + media_file.location #return make_response(jsonify({'username': user.username, # 'media_id': media_id, # 'file_location': media_file.location})) print response return Response(response)
def edit_post_post(post_id): selected_post = session.query(Post).filter_by(id=post_id).first() if selected_post.author_id != current_user.id: flash("Sorry, you do not have permission to edit this post", "danger") return redirect(url_for("dashboard")) else: post = session.query(Post).filter_by(id = post_id).first() post.title = request.form["title"] post.content = mistune.markdown(request.form["content"]) session.commit() return redirect(url_for("posts"))
def edit_post_get(post_id): posts = session.query(Post) count = session.query(Post).count() if post_id < 1 or post_id > count: return render_template("not_found.html") else: selected_post = posts.filter_by(id = post_id).first() if selected_post.author_id != current_user.id: flash("Sorry, you do not have permission to edit that post", "danger") return redirect(url_for('dashboard')) else: return render_template("edit_post.html", post = selected_post,)
def view_activity(activity_id=0): activity = session.query(Activity).get(activity_id) current = datetime.utcnow() past_24_hours = current - timedelta(hours=24) activity2 = session.query(Activity).filter(Activity.entry_date.between(current, past_24_hours)) print activity2 print activity2.all() return render_template('activity.html', activity=activity)
def post_delete(id): post = session.query(models.Post).get(id) if not post: message = "Could not find post with id {}".format(id) data = json.dumps({"message": message}) return Response(data, 404, mimetype="application/json") session.query(models.Post).filter(models.Post.id == id).delete(synchronize_session=False) posts = session.query(models.Post).all() data = json.dumps([post.as_dictionary() for post in posts]) return Response(data, 200, mimetype="application/json")
def login_post(): form = LoginForm(request.form) name = form.name.data password = form.password.data user = session.query(User).filter_by(username=name).first() if not user: # Try to find user via email user = session.query(User).filter_by(email=name).first() # If we STILL can't find user, or if password doesn't match, redirect if not user or not check_password_hash(user.password, password): flash('Incorrect username/email or password', 'danger') return redirect(url_for('login_get')) login_user(user) flash('Logged in successfully!', 'success') return redirect(request.args.get('next') or url_for('index'))
def song_delete(id): song = session.query(models.Song).get(id) if not song: message = "Could not find song with id {}".format(id) data = json.dumps({"message": message}) return Response(data, 404, mimetype="application/json") session.query(models.Song).filter(models.Song.id == id).delete(synchronize_session=False) posts = session.query(models.Song).all() data = json.dumps([song.as_dictionary() for song in songs]) return Response(data, 200, mimetype="application/json")
def posts_get(): """ Endpoint to retreive blog posts """ # Construct a query object from query string for title title_like = request.args.get("title_like") # Construct a query object from query string for body body_like = request.args.get("body_like") # Pass the query object to database and return all posts if available posts = session.query(models.Post) if title_like and body_like: posts = posts.filter(models.Post.title.contains(title_like)). \ filter(models.Post.body.contains(body_like)) elif title_like: posts = posts.filter(models.Post.title.contains(title_like)) elif body_like: posts = posts.filter(models.Post.body.contains(body_like)) else: posts = posts.all() # Convert posts to JSON format and return response data = json.dumps([post.as_dictionary() for post in posts]) return Response(data, 200, mimetype="application/json")
def _get_bucketlist_item(item_id, list_id): """Check that a bucketlist item exists.""" bucketlistitem = session.query( BucketListItems).filter_by(item_id=item_id, bucket_id=list_id).first() if not bucketlistitem: raise NoResultFound return bucketlistitem
def update_song(id): """ Updating a single song """ # check if the song exists, if not return a 404 with a helpful message song = session.query(models.Song).get(id) if not song: message = "Could not find song with id {}".format(id) data = json.dumps({"message": message}) return Response(data, 404, mimetype="application/json") data = request.json # check that the JSON supplied is valid # if not, return a 422 Unprocessable Entity try: validate(data, song_schema) except ValidationError as error: data = {"message": error.message} return Response(json.dumps(data), 422, mimetype="application/json") song.song_file = data["song_file"] session.commit() # return an OK 200, containing the song as JSON with the # location header set to the location of the post data = json.dumps(song.as_dictionary()) headers = {"Location": url_for("post_get", id=song.id)} return Response( data, 200, headers=headers, mimetype="application/json" )
def songs_post(): """ Post a new song to database """ data = request.json # Check for valid JSON. If not available, return 422, Unprocessable Entity try: validate(data, post_schema) except ValidationError as error: data = json.dumps({"message": error.message}) return Response(data, 422, mimetype="application/json") file_id = data["file"]["id"] song_file = session.query(models.File).get(file_id) if not song_file: # File with id = file_id is not in database message = "Could not find song file with file id {}".format(file_id) data = json.dumps({"message": message}) return Response(data, 404, mimetype="application/json") song = models.Song(file_id=file_id) session.add(song) session.commit() data = json.dumps(song.as_dictionary()) return Response(data, 201, mimetype="application/json")
def song_analyze(id): #check wether a song with the correct ID exists song = session.query(models.Song).get(id) if not song: message = "Could not find song with id {}".format(id) data = json.dumps({"message": message}) return Response(data, 404, mimetype="application/json") #get the filename of the song from the database song_file = session.query(models.File).filter_by(id=song.file_id).first() #save file to an upload folder using upload_path() function song_file_path = upload_path(song_file.filename) #call analyse function, passing in path of the uploaded file file_analysis = analysis.analyse(song_file_path) data = json.dumps(file_analysis) #return results of analysis function as a JSON object return Response(data, 201, mimetype="application/json")
def get_all_emotion(cls, emotion): """get all elements linked to a certain emotion""" elements_of_emotion = [] all_emotions = session.query(Element).filter_by(emotion=emotion).all() for a in all_emotions: elements_of_emotion.append(a) return elements_of_emotion
def get_all_type(cls, element_type): """get all elements of a certain type""" elements_of_type = [] all_types = session.query(Element).filter_by(element_type=element_type).all() for e in all_types: elements_of_type.append(e) return elements_of_type
def add_flavor(): """ Add a flavor to the DB """ # Get creator user name passed with request as argument creator = request.args.get("creator") # Get flavor name passed as argument flavor_name = request.args.get("flavor") # Try to get the flavor being added from the DB data = session.query(Flavor).filter(Flavor.name == flavor_name).all() # If you got the item back from the DB, issue a warning if data: message = {"message": "Entry matching request already exists in database."} return Response(json.dumps(message), 422, mimetype="application/json") # Otherwise create the flavor flavor = Flavor() flavor.name = flavor_name flavor.creator = creator # Add it to the DB session.add(flavor) session.commit() # Obtain the dict info for the created object data = flavor.as_dictionary() # And create the header for the new ingredient headers = {"Location": "/api/flavor/id/{}".format(flavor.id)} # Return that with 201 created return Response(json.dumps(data), 201, headers=headers, mimetype="application/json")