def adicionar_item_pedido(): produto_list = session.query(tbl_produto).order_by( tbl_produto.nome_produto).all() tb_ped = session.query(tbl_pedido).order_by(tbl_pedido.id_pedido).all() id = request.form.get('cod_produto') tb_prod = session.get(tbl_produto, id) print(id) if request.method == 'POST': # tbl_item quantidade_venda = request.form['quantidade_venda'] quantidade_venda = int(quantidade_venda) valor_unitario = request.form['id_valor_unitario'] valor_unitario = float(valor_unitario) cod_produto = request.form['id_cod_produto'] cod_pedido = request.form['id_pedido'] itens = tbl_item(quantidade_venda=quantidade_venda, valor_unitario=valor_unitario, cod_produto=cod_produto, cod_pedido=cod_pedido) session.add(itens) session.commit() session.close() return redirect(url_for('admin_pedido')) session.close() return render_template('adicionar_item_pedido.html', tb_ped=tb_ped, tb_prod=tb_prod, produto_list=produto_list)
def createRoutes(self): airports = session.query(Airport).all() routes = [] while (len(airports) != 0): origin = airports[0] airports.remove(airports[0]) for dest in airports: dist = calcDistanceKm(origin.geom, dest.geom) try: session.query(Route).filter_by( origin=origin.iata, destination=dest.iata).one() except NoResultFound: r1 = Route(origin=origin.iata, destination=dest.iata, distance=dist) session.add(r1) routes.append(r1) try: session.query(Route).filter_by( origin=dest.iata, destination=origin.iata).one() except NoResultFound: r2 = Route(origin=dest.iata, destination=origin.iata, distance=dist) session.add(r2) routes.append(r2) session.commit() return routes
def show_item(category_name, item_style): """Show a category and specific item.""" category = session.query(Category).filter_by( name=category_name).one_or_none() item = session.query(Item).filter_by(category=category, style=item_style).one_or_none() return render_template('item_detail.html', category=category, item=item)
def wrapper(*args, **kwds): category_name = kwds["category_name"] item_style = kwds["item_style"] # 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, style=item_style).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 the owner of this item. " "You do not have permission to edit/delete.") return redirect("/catalog/{}/items".format(category_name)) kwds['item_style'] = item_style return f(*args, **kwds)
def adicionar_pedido_pj(): cliente_pj = session.query(tbl_pessoa_juridica).order_by( tbl_pessoa_juridica.razao_social).all() status_list = session.query(tbl_status_pedido).order_by( tbl_status_pedido.id_status).all() if request.method == 'POST': # tbl_pedido cod_cliente = request.form['cod_cliente'] mod_pgto = request.form['mod_pgto'] cod_status = request.form['cod_status'] desconto = 0 pedido = tbl_pedido(data_pedido=datetime.now(), cod_cliente=cod_cliente, desconto=desconto, cod_status=cod_status, mod_pgto=mod_pgto) session.add(pedido) session.commit() session.close() return redirect(url_for('admin_pedido')) session.close() return render_template('adicionar_pedido_pj.html', cliente_pj=cliente_pj, status_list=status_list)
def section_full_list(): """ Возвращает полный список разделов с подсчетом количества групп и постов в каждом разделе, а также выводит данные по последнему пользователю, написавшему пост в данном разделе """ max_dt_query = session.query( Post.thread_id, Post.author, func.max(Post.created).label('created_dt'), User.username).join(User).group_by( Post.thread_id).subquery().alias('max_dt_query') post_subquery = session.query( Post.thread_id, func.count('*').label('count'), max_dt_query.c.created_dt, max_dt_query.c.username ).outerjoin(max_dt_query, Post.thread_id == max_dt_query.c.thread_id)\ .group_by(Post.thread_id).subquery().alias('post_subquery') thread_subquery = session.query( Thread.section_id, func.count('*').label('thread_count'), func.sum(post_subquery.c.count).label('post_count'), post_subquery.c.created_dt, post_subquery.c.username).outerjoin(post_subquery).group_by( Thread.section_id).subquery() queryset = session.query( Section.id, Section.name, Section.description, Section.tag, thread_subquery.c.thread_count, thread_subquery.c.post_count, thread_subquery.c.created_dt, thread_subquery.c.username).outerjoin(thread_subquery) response = section_list_schema.dump(queryset) json_response = jsonify(response) return make_response(json_response, 200)
def put(self, id): data = request.json try: user = session.query(User).get(id) if "username" in data: user.username = data["username"] if "first_name" in data: user.first_name = data["first_name"] if "last_name" in data: user.last_name = data["last_name"] if "email" in data: user.email = data["email"] if "password" in data: user.password = data["password"] if "groups" in data: session.query(Invited).filter( Invited.user_id == user.id).delete() for group in data["groups"]: invited = Invited(user.id, group) session.add(invited) session.commit() return Response(response=json.dumps({"message": "Success"}), status=200, mimetype="application/json") except Exception as e: return Response(response=json.dumps({"message": "Invalid input"}), status=405, mimetype="application/json")
def category(category_name): ''' provides list of items associated to a category ''' category = session.query(Category).filter_by(name=category_name).one() items = session.query(Item).filter_by(category_id=category.id) return render_template('category.html', category=category, items=items)
def add_host(): if not request.json: abort(400) else: data = request.json old_nodes = session.query( models.Node).filter_by(management_ip=data.get('management_ip')).all() if len(old_nodes) != 0: return {"status": "Node da ton tai"} node = models.Node(created_at=datetime.now(), updated_at=datetime.now(), deleted_at=None, management_ip=data.get('management_ip', ""), ssh_user=data.get('ssh_user', ""), ssh_password=data.get('ssh_password', ""), status="set_ip", node_display_name=data.get('node_display_name', '')) session.add(node) session.commit() new_node = session.query(models.Node).filter_by( node_display_name=str(data.get('node_display_name', ''))).all() #print(models.to_json(new_node, 'Node',True)) return jsonify(models.to_json(new_node, 'Node', True)), 201
def search_user(cls, id: int = None, login: str = None, token: str = None) -> None or 'User': """ Ищет пользователя в базе по id :param id: :param token: :param login: :return: """ if id is not None: user = session.query(cls).filter_by(id=id).first() elif (login and token) is not None: user = session.query(cls).filter_by(login=login, token=token).first() elif login is not None: user = session.query(cls).filter_by(login=login).first() elif token is not None: user = session.query(cls).filter_by(token=token).first() else: return None return user
def get(id=None, title=None): alls = [] if not id and not title: homes = session.query(Homes).all() elif id: homes = session.query(Homes).filter_by(id=id).all() elif title: homes = session.query(Homes).filter_by(title=title).all() for h in homes: alls.append({ 'Titulo': h.title, 'Valor': h.value, 'Descricao': h.description, 'Endereco': [{ 'Rua': h.street, 'Numero': h.number, 'Complemento': h.complement, 'Bairro': h.neighborhood, 'CEP': h.zipCode }], 'Telefone': h.telephone }) return jsonify({'republicas': alls})
def index(): ''' Display list of categories & items ''' categories = session.query(Category) items = session.query(Item).order_by(Item.id.desc()).limit(10) return render_template('index.html', items=items, categories=categories)
def deleteItem(item_name, category_name): ''' Deletes item, only allows creator to delete ''' # check if user is logged in if not 'user_id' in login_session: flash("You need to be logged-in to perform this action", 'error') return redirect('/') item = session.query(Item).filter_by(name=item_name).one() # check if user has permission if login_session['user_id'] != item.user_id: flash("You do not have permissions to edit this item", 'error') return redirect('/') if request.method == 'POST': session.delete(item) session.commit() category = session.query(Category).filter_by( name=category_name).first() itemsLeft = session.query(Item).filter_by(category=category).first() # if there are no more items in category delete it. if itemsLeft == None: session.delete(category) session.commit() flash("menu item deleted!", 'success') return redirect('/') else: return render_template( 'deleteitem.html', item=item)
def put(self, bucketlist_id, item_id): """ Called with a PUT request """ bucketlist = session.query(Bucketlist).filter_by( id=bucketlist_id, created_by=self.current_user).first() if not bucketlist: return 'Bucketlist does not exist', 404 request_args = self.parse_args() # Missing item name if not request_args.get('name') and not request_args.get('done'): return 'Item name needed', 400 item = session.query(Item).filter_by(id=item_id, bucketlist=bucketlist).first() if not item: return 'Item does not exist', 404 try: if request_args.get('name'): item.name = request_args.get('name') if request_args.get('done'): item.completed = request_args.get('done') self.save(item) return 'Item updated', 200 except IntegrityError: session.rollback() return 'Item name already exists', 409
def get_role_info(role_id): with open('static/role_service.json') as role_data_file: role_data = json.load(role_data_file) print(role_data.keys()) role_info = [{ "role_name": role_name, "role_inf": role_data[role_name] } for role_name in role_data.keys() if role_data[role_name]['id'] == role_id] if len(role_info) == 0: return {"status: ": "Role id not found"} role_node = [] list_node_role = session.query( models.Node_role).filter_by(role_name=role_info[0]["role_name"]).all() for node_role in list_node_role: node = session.query( models.Node).filter_by(node_id=node_role.node_id).first() role_node.append(models.to_json(node, 'Node', False)) session.close() return {"status": "OK", "role_info": role_info[0], "role_node": role_node}
def addcomment(sub, post): if sub == 'food' or sub == 'pizza' or sub == 'sushi': getquote = session.query(FoodStuff).order_by(func.rand()).first() print("sub", sub) try: post.reply(str(getquote.comment)) except Exception as e: print(str(e)) pass print("Comment: ", getquote.comment) print("") elif sub == 'funny': getquote = session.query(FunnyStuff).order_by(func.rand()).first() print(getquote.id) try: post.reply(str(getquote.comment)) except Exception as e: print(str(e)) pass print("Comment: ", getquote.comment) else: print("No Sub Found") pass
def add_saved_meal_post(): #don't use the reequest.args.get('user') to avoid malicious user. #user_id incorporates the user_id via flask. user = current_user meal_name = request.args.get('meal_name') #query the data base Meal. meal = session.query(Meal).filter_by(name=meal_name, user_id=user.id).first() food_log = get_food_log(user) for food in meal.foods: #food is the name of the food in the MealFoodAssociation #create a new FoodLogFoodAssociation() for each MealFoodAssociation flfa = FoodLogFoodAssociation() #copy over the attributes of the MealFoodAssociation to FoodLogFoodAssociation flfa.food_NDB_No = food.food_NDB_No flfa.unit_Seq = food.unit_Seq flfa.quantity = food.quantity #append FoodLogFoodAssociation to food_log.foods food_log.foods.append(flfa) #send back this info to the client side via html which will then #be sent to the javascript which will insert the info on the page. session.commit() nutrient_definitions = session.query(NutrientDefinition).all() #fix me-should pass targets in. foods = build_food_list(meal.foods, nutrient_definitions) return render_template('partial_food_log.html', foods=foods)
def postSearchUrl(self, departure_airport, arrival_airport, departure_date, base_url=BASE_URL, api_key=API_KEY_2XT): try: baseUrl = session.query(BaseUrl).filter_by(base_url=base_url.strip()).one() except NoResultFound: baseUrl = BaseUrl(base_url=base_url) session.add(baseUrl) session.commit() try: apiKey = session.query(ApiKey).filter_by(api_key=api_key).one() except NoResultFound: apiKey = ApiKey(api_key=api_key) session.add(apiKey) session.commit() searchUrl = SearchUrl(base_url=baseUrl.base_url_id, api_key=apiKey.api_key_id, departure_airport=departure_airport, arrival_airport=arrival_airport, departure_date=departure_date) session.add(searchUrl) session.commit() return searchUrl
def section_thread_list(section_id): """ Возвращает список тем для выбранного раздела с подсчетом количества ответов и просмотров, а также выводит данные по последнему пользователю, написавшему пост в данном разделе """ max_dt_query = session.query( Post.thread_id, Post.author, func.max(Post.created).label('created_dt'), User.username).join(User).group_by( Post.thread_id).subquery().alias('max_dt_query') post_subquery = session.query( Post.thread_id, func.count('*').label('post_count'), max_dt_query.c.created_dt, max_dt_query.c.username ).outerjoin(max_dt_query, Post.thread_id == max_dt_query.c.thread_id)\ .group_by(Post.thread_id).subquery().alias('post_subquery') queryset = session.query( Thread.id, Thread.name, Thread.created, Thread.section_id, Thread.views, post_subquery.c.post_count, post_subquery.c.created_dt, post_subquery.c.username).outerjoin(post_subquery).filter( Thread.section_id == section_id).order_by(Thread.created.desc()) response = thread_list_schema.dump(queryset) json_response = jsonify(response) return make_response(json_response, 200)
def serialize_fit_route(route_info, seats_info): arr_station_name = session.query(Station).get( route_info[2].station_id).name dep_station_name = session.query(Station).get( route_info[1].station_id).name route_name = session.query(BaseRoute).get( route_info.Schedule.base_route_id).name route_info_dict = { 'departure_time': route_info[1].departure, 'arrival_time': route_info[2].arriving, 'schedule_id': route_info[0].id, 'dep_stop_id': route_info[1].station_id, 'arr_stop_id': route_info[2].station_id, 'arr_station_name': arr_station_name, 'dep_station_name': dep_station_name, 'route_name': route_name, 'seats_info': [] } for type_name, type_info in seats_info.items(): route_info_dict['seats_info'].append({ 'type_name': type_name, 'num_of_places': type_info['num_of_places'], 'cost': type_info['cost'] }) return route_info_dict
def get_tickets(**kwargs): if (kwargs.get('usr_email') is not None): return session.query(Ticket).join(User, User.id == Ticket.user_id). \ filter(User.email == kwargs.get('usr_email')).all() if (kwargs.get('ticket_id') is not None): return [session.query(Ticket).get(kwargs.get('ticket_id'))] return []
def on_get(self, req, resp, teacherid): teacher = sess.query(ms.Teacher).get(teacherid) if teacher is None: resp.status = falcon.HTTP_404 resp.body = "A teacher with the idea of %s was not found." % teacherid return today = datetime.date.today() default = teacher.home_room_students removedstudents = sess.query(ms.Student).join(ms.Schedule).filter(ms.Student.home_room_teacher_id == teacherid, ms.Schedule.date == today) default = [e for e in default if e not in removedstudents] newstudents = sess.query(ms.Student).join(ms.Schedule).filter(ms.Schedule.teacher_id == teacherid, ms.Schedule.date == today) moved = [student.to_dict() for student in removedstudents] default = [student.to_dict() for student in default] new = [student.to_dict() for student in newstudents] temp_list = list(default) temp_list.extend(new) for student_dict in temp_list: # req.log_error(str(student_dict)) if sess.query(ms.Absence).get((student_dict["id"], today)) is not None: student_dict["absent"] = True # req.log_error(str(student_dict)) resp.status = falcon.HTTP_200 resp.body = json.dumps({"moved": moved, "default": default, "new": new})
def editItem(item_name, category_name): ''' Form to add edit items, only allows creator to edit ''' # check if user is logged in if not 'user_id' in login_session: flash("You need to be logged-in to perform this action", 'error') return redirect('/') form = addItemForm() categories = session.query(Category) item = session.query(Item).filter_by(name=item_name).first() category = session.query(Category).filter_by(name=category_name).first() # check if user has permission if login_session['user_id'] != item.user_id: flash("You do not have permissions to edit this item", 'error') return redirect('/') if request.method == 'POST' and form.validate(): # add new info to item updateItem(form, item) flash("Item updated!", 'success') return redirect('/') else: return render_template('edititem.html', item=item, form=form, \ category=category, categories=categories)
def deleteItem(item_name, category_name): ''' Deletes item, only allows creator to delete ''' # check if user is logged in if not 'user_id' in login_session: flash("You need to be logged-in to perform this action", 'error') return redirect('/') item = session.query(Item).filter_by(name=item_name).one() # check if user has permission if login_session['user_id'] != item.user_id: flash("You do not have permissions to edit this item", 'error') return redirect('/') if request.method == 'POST': session.delete(item) session.commit() category = session.query(Category).filter_by( name=category_name).first() itemsLeft = session.query(Item).filter_by(category=category).first() # if there are no more items in category delete it. if itemsLeft == None: session.delete(category) session.commit() flash("menu item deleted!", 'success') return redirect('/') else: return render_template('deleteitem.html', item=item)
def get_current_installation_status(): current_task = session.query( models.Task).filter_by(status='INPROCESSING').first() if current_task is None: current_task = session.query( models.Task).filter_by(status='FAILED').first() if current_task is None: current_task = session.query(models.Task).filter_by( status='DONE').order_by(models.Task.finished_at.desc()).all() if current_task is not None: current_task = current_task[0] if len(current_task) > 0 else None if current_task is None: return abort(404, "No Task was Run") current_service = current_task.service_setup current_node = current_service.deployment.node res = { " current_task": models.to_json(current_task, 'Task', False), "current_service": models.to_json(current_service, 'Service_setup', False), "current_node": models.to_json(current_node, 'Node', False), } session.commit() session.close() return res, 200
def get(self): args = parser.parse_args() if 'page_now' not in args: return err_res(code=0, msg='no page_now') if 'page_size' not in args: return err_res(code=0, msg='no page_size') page_now = args['page_now'] page_size = args['page_size'] if page_now * page_size > 250: return err_res(code=0, msg='无更多电影') cached_movies = session.query(Movie).filter( Movie.id.between((page_now - 1) * page_size + 1, page_now * page_size)).all() if len(cached_movies): return success_res(code=1000, data=cached_movies, msg='success') try: spider = Spider() movies = spider.get_movies(const.BASE_URL) for movie in movies: create_movie(movie) cached_movies = session.query(Movie).filter( Movie.id.between((page_now - 1) * page_size + 1, page_now * page_size)).all() return success_res(code=1000, data=cached_movies, msg='success') except: return err_res(code=0, msg='err')
def home(): count = 0 if request.method == 'POST': print("Got new request") username = request.form.getlist('username') print("username is: ", username) user = session.query(User).filter(User.username.in_(username)).all() print("User is: ", user) if user is None: if username != "all": raise Exception("No user found!") locations = session.query(Location) if username == "all": locations = locations.all() else: locations = locations.filter(Location.user_id.in_([u.id for u in user])).all() print("Data length is: {}".format(len(locations))) count = len(locations) locations = json.dumps(locations, cls=AlchemyEncoder) else: locations = "" users = session.query(User).all() return render_template("index.html", data=locations, users=users, count=count)
def get_ads_info(page=None, sort=None): sort_list = { "price_asc": Ads.price.asc(), "price_desc": Ads.price.desc(), "date_asc": Ads.data_create.asc(), "date_desc": Ads.data_create.desc(), } if sort is None: ads = session.query(Ads).all() elif sort in sort_list: ads = session.query(Ads).order_by(sort_list[sort]).all() if ads: ads_list = [] if page is not None: for ad in ads[(page-1)*10:(page)*10]: ad = {'name': ad.name, 'price': ad.price, 'url': ad.main_url} ads_list.append(ad) session.expire_all() return jsonify(f'page {page}. Ads from {(page-1)*10+1} to {(page)*10}', ads_list), 200 else: for ad in ads: ad = {'name': ad.name, 'price': ad.price, 'url': ad.main_url} ads_list.append(ad) session.expire_all() return ads_list, 200 else: raise TableIsEmpty
def get_empty_places(**kwargs): schedule = session.query(Schedule).get(kwargs.get('schedule_id')) print(kwargs.get('schedule_id')) arrival_stop = session.query(Stop).get(kwargs.get('dep_stop_id')) print(kwargs.get('dep_stop_id')) departure_stop = session.query(Stop).get(kwargs.get('arr_stop_id')) print(kwargs.get('arr_stop_id')) return get_detailed_seats_info(schedule, arrival_stop, departure_stop)
def updatePriceKm(self): trips = session.query(Trip).all() for trip in trips: dist = session.query(Route).filter_by( route_id=trip.route).one().distance trip.price_km = float(trip.price) / dist session.commit()
def users(): result_users = session.query(User) #.join(User.address).all() result_addresses = session.query(Address) print session.query(User).count() return render_template('user.html', users=result_users, addresses=result_addresses)
def users(): result_users = session.query(User)#.join(User.address).all() result_addresses = session.query(Address) print session.query(User).count() return render_template('user.html', users=result_users, addresses=result_addresses)
def show(): # 分组统计 query_result = session.query( extract('day', SinaCommentSentiment.time).label('day'), func.count('day')).group_by('day').all() showData = tupleListToDictList(query_result) sentiments = session.query(SinaCommentSentiment.sentiment).all() pn = process(sentiments) return render_template('/home/show.html', showData=showData, pn=pn)
def showCatalog(): catalog = session.query(Category).order_by(asc(Category.name)) latestItems = session.query(Item.name, Item.id, Category.name, Category.id).join(Category).order_by( desc(Item.id)).limit(10) latest = [] for (itemName, itemId, categoryName, categoryId) in latestItems: latest.append( {'item_name': itemName, 'category_name': categoryName, 'item_id': itemId, 'category_id': categoryId}) return render_template('catalog/catalog.html', catalog=catalog, latest=latest)
def categoryCheck(form): ''' Checks if parsed category name exists, if not it creates one ''' category = session.query(Category).filter_by(name=form.category.data).first() if category == None: newCategory = Category(name=form.category.data, user_id=login_session['user_id']) session.add(newCategory) session.commit() category = session.query(Category).filter_by(name=form.category.data).first() return category
def catalogJSON(): categories = session.query(Category).all() dict = {'Category': []} for cat in categories: cat_dict = cat.serialize items_dict = [] items = session.query(Item).filter_by(category_id=cat.id) for item in items: items_dict.append(item.serialize) cat_dict['Item'] = items_dict dict['Category'].append(cat_dict) return jsonify(dict)
def readSkus(price_list_id): if 'username' not in login_session: return redirect('/oauth/login') else: pass #Database query for all the possible brands using the distinct() method brands = session.query(Sku.name).filter_by(price_list_id=price_list_id).distinct() for brand in brands: print brand.name.upper() item = session.query(PriceList).filter_by(id=price_list_id).one() skus = session.query(Sku).filter_by(price_list_id=price_list_id).all() return render_template('pxlst/readSkus.html', price_list_id=price_list_id, price_list=item, skus=skus, brands=brands)
def on_get(self, req, resp): teacher_id, student_id, date =\ req.get_param("teacher_id"), req.get_param("student_id"), req.get_param("date") date = datetime.datetime.strptime(date, "%Y-%m-%d").date() new_teacher = sess.query(ms.Teacher).get(teacher_id) student = sess.query(ms.Student).get(student_id) old_teacher = sess.query(ms.Teacher).get(student.home_room_teacher_id) schedule = sess.query(ms.Schedule).get((student_id, teacher_id, date)) dict = schedule.to_dict() dict["student"] = student.to_dict() dict["new_teacher"] = new_teacher.to_dict() dict["old_teacher"] = old_teacher.to_dict() resp.status = falcon.HTTP_200 resp.body = json.dumps(dict)
def createSku(price_list_id): if 'username' not in login_session: return redirect('/oauth/login') else: pass if request.method == 'POST': price = int(request.form.get('price')) if request.form.get('price2'): price2 = int(request.form.get('price2')) pxlist = price_list_id user_id = getUserID(login_session['email']) newSku = Sku(name = request.form['name'], varietal = request.form['varietal'], price = price, price2 = price2, price_list_id=pxlist, user_id=user_id) session.add(newSku) session.commit() flash('new sku item created!') return redirect(url_for('pxlst.readSkus', price_list_id=price_list_id)) pxlist = session.query(PriceList).filter_by(id=price_list_id).one() #protection from non creator if login_session['username'] != pxlist.user.name: flash("Debes ser el creador de la lista para crear un nuevo Sku.") return redirect(url_for('pxlst.readSkus', price_list_id=price_list_id)) else: return render_template('pxlst/createSku.html', price_list_id=price_list_id)
def getVideosJSON(): json_text = [] q = session.query(Video) vids = q.order_by(Video.id).all() for vo in vids: json_text.append({"rank": vo.getRank(), "title": vo.title, "query": vo.query, "id": vo.ytid, "viewers": vo.viewers, "timestamp": vo.getDateTimeLastPlayed(), "length": vo.length, "watched": vo.watched, "skips": vo.skips, "percentageWatched": vo.getPercentageWatched()}) return json_text
def login(): #login_manager = LoginManager() #login_manager.init_app() form = LoginForm(request.form) #form = LoginForm() #if form.validate_on_submit(): if request.method == 'POST' and form.validate(): #want to find the user with the username or email address as enterred user = session.query(User).filter( (User.email == form.username_or_email.data) | (User.username == form.username_or_email.data) ).first() #want to check to see if the user is registered and password info is correct. if user is None or not check_password_hash(user.password, form.password.data): flash("Your login information is incorrect. Please try again.") return redirect(url_for('login')) #check to see if the password is correct. #then log in the user login_user(user) flash("Logged in successfully.") return redirect(url_for('food_log_get')) return render_template( 'login.html', title='Sign In', form=form #providers=app.config['OPENID_PROVIDERS']) )
def food_log_post(): user = current_user quantity = request.form.get('quantity') unit = request.form.get('unit') unit = json.loads(unit) food_log = get_food_log(user) association = FoodLogFoodAssociation( food_NDB_No=unit["NDB_No"], unit_Seq=unit["Seq"], quantity=float(quantity) ) food_log.foods.append(association) #build the query favorite_query = session.query(FavoriteAssociation) favorite_query = favorite_query.filter_by(NDB_No=unit["NDB_No"], user_id=user.id) #executing the query favorite = favorite_query.first() if favorite == None: favorite = FavoriteAssociation( NDB_No=unit["NDB_No"], user_id=user.id, popularity=1 ) session.add(favorite) else: favorite.popularity += 1 session.commit() return redirect(url_for('food_log_get'))
def updateSku(price_list_id, sku_id): if 'username' not in login_session: return redirect('/oauth/login') else: pass sku = session.query(Sku).filter_by(id=sku_id).one() if request.method == 'POST': if request.form.get('name'): sku.name = request.form['name'] if request.form.get('varietal'): sku.varietal = request.form['varietal'] if request.form.get('price'): sku.price = int(request.form['price']) if request.form.get('price2'): sku.price2 = int(request.form['price2']) session.add(sku) session.commit() print 'sku commited' flash("sku editado!") return redirect(url_for('pxlst.readSkus', price_list_id=price_list_id)) #protection from non creator if login_session['username'] != sku.user.name: flash("Debes ser el creador de la lista para editar este Sku.") return redirect(url_for('pxlst.readSkus', price_list_id=price_list_id)) else: return render_template('pxlst/updateSku.html', price_list_id=price_list_id, sku_id=sku_id, sku=sku)
def createUser(login_session): newUser = User(name=login_session['username'], email=login_session[ 'email'], picture=login_session['picture']) session.add(newUser) session.commit() user = session.query(User).filter_by(email=login_session['email']).one() return user.id
def updatePricelist(price_list_id): if 'username' not in login_session: return redirect('/oauth/login') else: pass item = session.query(PriceList).filter_by(id=price_list_id).one() if request.method == 'POST': if request.form.get('name'): item.name = request.form['name'] if request.form.get('communicated'): item.communicated = datetime.datetime.strptime(request.form['communicated'], '%Y-%m-%d') if request.form['vigente'] == 'True': item.vigente = True else: item.vigente = False session.add(item) session.commit() flash("lista de precios editada!") return redirect(url_for('pxlst.readPricelists')) #protection from non creator if login_session['username'] != item.user.name: flash("Debes ser el creador de la lista para editarla.") return redirect(url_for('pxlst.readPricelists')) else: return render_template('pxlst/updatePricelist.html', price_list_id=price_list_id, item=item)
def on_post(self, req, resp): today = datetime.date.today() absent = req.get_param_as_list("absent") # req.log_error(" ".join(absent)) present = req.get_param_as_list("present") # req.log_error(" ".join(present)) for stid in absent: if sess.query(ms.Absence).get((stid, today)) is None: sess.add(ms.Absence(stid, today)) for stid in present: temp = sess.query(ms.Absence).get((stid, today)) if temp is not None: sess.delete(temp) sess.commit() resp.status = falcon.HTTP_200 resp.body = "Attendance Successfully Taken"
def on_get(self, req, resp): field = req.get_param("f") if not (field in ms.Student.completable): resp.status = falcon.HTTP_400 resp.body = "Invalid Field" return mf = getattr(ms.Student, field) toq = req.get_param("q") if toq is None: resp.status = falcon.HTTP_400 resp.body = "No Query Found" return page = req.get_param("p") page = int(page) if page else 1 query = sess.query(ms.Student).filter(mf.like("%s%%" % toq)) count = query.count() if (page-1)*10 > count: resp.status = falcon.HTTP_404 resp.body = "Page not found" return resp.status = falcon.HTTP_200 resp.body = json.dumps({"students": [student.to_dict() for student in query.order_by(mf).slice((page-1)*10, page*10).all()], "page": page, "amount": count})
def on_get(self, req, resp, teacherid, year, month, day): teacher = sess.query(ms.Teacher).get(teacherid) if teacher is None: resp.status = falcon.HTTP_404 resp.body = "A teacher with the idea of %s was not found." % teacherid return date = datetime.date(year, month, day) default = teacher.home_room_students removedstudents = sess.query(ms.Student).join(ms.Schedule).filter(ms.Student.home_room_teacher_id == teacherid, ms.Schedule.date == date) default = [e for e in default if e not in removedstudents] newstudents = sess.query(ms.Student).join(ms.Schedule).filter(ms.Schedule.teacher_id == teacherid, ms.Schedule.date == date) resp.status = falcon.HTTP_200 resp.body = json.dumps({"moved": [student.to_dict() for student in removedstudents], "default": [student.to_dict() for student in default], "new": [student.to_dict() for student in newstudents]})
def on_get(self, req, resp, teacherid): teacher = sess.query(ms.Teacher).get(teacherid) if teacher is None: resp.status = falcon.HTTP_404 resp.body = "A teacher with the idea of %s was not found." % teacherid return resp.status = falcon.HTTP_200 resp.body = json.dumps([student.to_dict() for student in teacher.home_room_students])
def on_get(self, req, resp, teacherid): teacher = sess.query(ms.Teacher).get(teacherid) if teacher is None: resp.status = falcon.HTTP_404 resp.body = "A teacher with the id of %s was not found." % teacherid return resp.status = falcon.HTTP_200 resp.body = json.dumps(teacher.to_dict())
def get_food_log(user): food_log = session.query(FoodLog).filter_by(user=user).first() if food_log is None: food_log = FoodLog() food_log.user = user session.add(food_log) session.commit() return food_log
def readUnfilteredPricelists(): if 'username' not in login_session: return redirect('/oauth/login') else: pass picture = login_session['picture'] items = session.query(PriceList).all() return render_template('pxlst/readUnfilteredPricelists.html', price_lists=items, picture=picture)
def saved_meal_post(): #don't use the reequest.args.get('user') to avoid malicious user. user = current_user #request.args.get('meal_name') gets the value associated #with the query string 'meal_name' #ex: /add_saved_meal_post?meal_name=breakfast selected_foods = request.args.get('selected_foods') meal_name = request.args.get('meal_name') #think about keys and values. look at the flask documentation for requesting #keys and values. #do not use 'if not selected_foods' because the id of 0 evaluates to False. if selected_foods == None or selected_foods == "": return "" #need to first strip leading and trailing commas to create a clean and valid list #of strings separated by commas. selected_foods = selected_foods.strip(",").split(',') #create an instance of the Meal model #creating a Meal object by calling the Meal constructor. #can set any column values as identified in the models, in this case models/meal.py #creating a name for the saved_meal saved_meal = Meal(name=meal_name) #loop through the food_ids to save the selected foods as a meal. #selected_foods is a list. for food_id in selected_foods: #making an instance of the Class MealFoodAssociation meal_food_association = MealFoodAssociation() #query the FoodLogFoodAssociation table to get the row (the matching association) that has the specific #food_id. food_log_food_association = session.query(FoodLogFoodAssociation).get(int(food_id)) #access the attribute of the variable which is an instance of the class #copy the attributes from the food_log_food_association to the #attribute mealfoodassociation #integer primary keys are automatically filled in. meal_food_association.food_NDB_No = food_log_food_association.food_NDB_No meal_food_association.unit_Seq = food_log_food_association.unit_Seq meal_food_association.quantity = food_log_food_association.quantity #add the saved food to the Meal saved_meal.foods.append(meal_food_association) #append the saved _meal to the list user.meals #save it once. Take it out of the for loop. user.meals.append(saved_meal) #save the meal session.add(saved_meal) session.commit() #returning an empty string is saying that the code works. return ""
def get_food_log(user, date=None): if date is None: date = datetime.date.today() food_log = session.query(FoodLog).filter_by(user=user, date=date).first() if food_log is None: food_log = FoodLog() food_log.user = user session.add(food_log) session.commit() return food_log
def selected_food_groups(): user = current_user # Get and parse a comma-seperated query string food_groups = request.args.get('food_groups') if food_groups == None: return "" food_groups = food_groups.split(',') # user.selected_food_groups is linked to the nutrition database. session.query(UserFoodGroupAssociation).delete() for code in food_groups: association = UserFoodGroupAssociation( food_group_code=code ) user.selected_food_groups.append(association) session.commit() return ""
def query_foods(query_string): # construct a list of all the groups that we want to use as filters. # groups is a list of numbers # request.args.get list : we are looking for ?group groups = request.args.getlist("group") group_filters = [FoodDescription.FdGrp_Cd == group for group in groups] foods = session.query(FoodDescription) foods = foods.filter(FoodDescription.Long_Desc.ilike('%{}%'.format(query_string))) #finds the foods in all the foods and group_filters. foods = foods.filter(or_(*group_filters)) #this limit needs to be raised or eliminated #once I incorporate PostgreSQL, elastic, or Lucene #as a more precise search tool. foods = foods.limit(20) food_list = [] for food in foods: #find all the weights that match the foods. unit_query = session.query(Weight).filter(Weight.NDB_No == \ food.NDB_No).all() unit_list = [] for unit in unit_query: unit_list.append({ "name": unit.Msre_Desc, "Gm_Wgt": unit.Gm_Wgt, "NDB_No": unit.NDB_No, "Seq": unit.Seq, "amount": unit.Amount, }) food_list.append({ "name": food.Long_Desc, "units": unit_list }) #to reference units this is the code: #food_list[0] #food_list[0]["units"] #to test queries: type localhost:5000/queries/butter, salted.json return json.dumps(food_list)