def post(self): product_collection = request.get_json() if not product_collection: response = {'message': 'No input data provorder_ided'} return response, HttpStatus.bad_request_400.value #errors = product_schema.validate(product_collection) #if errors: #return errors, HttpStatus.bad_request_400.value product_name = product_collection['name'] if not Product.is_name_unique(id=0, name=product_name): response = {'error': 'Product already exist'.format(product_name)} return response, HttpStatus.bad_request_400.value try: product_category_name = product_collection['product_category'] category = ProductCategory.query.filter_by( name=product_category_name).first() if category is None: category = ProductCategory(name=product_category_name) db.session.add(category) product = Product(name=product_collection['name'], price=product_collection['price'], description=product_collection['description'], product_category=category, tags=product_collection['tags']) product.add(product) query = Product.query.get(product.id) dump_result = product_schema.dump(query) return dump_result, HttpStatus.created_201.value except SQLAlchemyError as e: db.session.rollback() response = {"error": str(e)} return response, HttpStatus.bad_request_400.value
def dbbuild(): db.drop_all() db.create_all() admin1 = User(username='******', password='******', role=1, email='*****@*****.**', gender='1') admin2 = User(username='******', password='******', role=2, email='*****@*****.**', gender='2') admin3 = User(username='******', password='******', role=3, email='*****@*****.**', gender='1') admin4 = User(username='******', password='******', role=4, email='*****@*****.**', gender='2') product1 = Product(product_name='生产中的商品', status='1', number='1', description='description1') product2 = Product(product_name='待运输的商品', status='2', number='2', description='description2') product3 = Product(product_name='运输中的商品', status='3', number='3', description='description3') product4 = Product(product_name='已到达的商品', status='4', number='4', description='description4') product5 = Product(product_name='已入库的商品', status='5', number='5', description='description5') db.session.add(admin1) db.session.add(admin2) db.session.add(admin3) db.session.add(admin4) db.session.add(product1) db.session.add(product2) db.session.add(product3) db.session.add(product4) db.session.add(product5) db.session.commit() click.echo('表已初始化.')
def create_product(product_id=None,product_name=None): if product_id is None or len(product_id) <= 3: product_id = random_key(10) product = Product(product_id=product_id,product_name=product_name) product.put() import logging logging.error(product.properties()) return product
def bids(): p_bids = Product() query_bids = p_bids.query.order_by(p_bids.owner_id).all() user_bids = User.query.filter_by(id=session['user_id']).first() username_session = user_bids.username if request.method == 'POST': try: bptype = request.form['inputBptype'] bprice = request.form['inputBprice'] owner = user_bids.get_id() if bptype and bprice: b = Bid( bidder=owner, product=bptype, bid_price=bprice, ) db.session.add(b) db.session.commit() msg = "New bid added." flash(msg) p_fbid = Product() query_fbid = p_fbid.query.order_by(p_fbid.owner_id).all() user = User.query.filter_by(id=session['user_id']).first() username_session = user.username firstname_session = user.first_name lastname_session = user.last_name email_session = user.email return render_template('products.html', obj=query_fbid, session_user_name=username_session, session_first_name=firstname_session, session_last_name=lastname_session, session_email=email_session) else: flash('Enter all the Required Fields') p_sid = Product() query_sid = p_sid.query.order_by(p_sid.owner_id).all() user = User.query.filter_by(id=session['user_id']).first() username_session = user.username firstname_session = user.first_name lastname_session = user.last_name email_session = user.email return render_template('products.html', obj=query_sid, session_user_name=username_session, session_first_name=firstname_session, session_last_name=lastname_session, session_email=email_session) except Exception as e: return json.dumps({'error': str(e)}) return render_template('products.html', obj=query_bids, session_user_name=username_session)
def book_queue(): p_bids = Product() if request.method == 'POST': if request.form['inputaddqueue'] == 'Yes': p_bids = Product() usr_bids = User.query.filter_by(id=session['user_id']).first() username_session = usr_bids.username firstname_session = usr_bids.first_name lastname_session = usr_bids.last_name email_session = usr_bids.email #ibook_from = request.form['ibooked_from'] #ibook_to = request.form['ibooked_to'] ibook_from = "12-14-2017 00:00:00" ibook_to = "12-15-2017 00:00:00" ibook_id = request.form['ibooked_pid'] query_q_fbid = p_bids.query.filter_by(id=ibook_id).first() query_p_all = p_bids.query.order_by(desc( Product.id)).limit(3).all() res_add_q = add_d_q(ibook_from, ibook_to, ibook_id, usr_bids.id) p_str = "As requested you have been added to the queue of the below item" if res_add_q: return render_template('booking.html', obj_str=p_str, obj_all=query_p_all, book_q_from=ibook_from, book_q_to=ibook_to, book_st=False, obj_pid=query_q_fbid.id, obj_ptype=query_q_fbid.product_type, obj_ptitle=query_q_fbid.title, obj_pprice=query_q_fbid.sale_price, session_user_name=username_session, session_first_name=firstname_session, session_last_name=lastname_session, session_email=email_session) else: p_str = "Sorry, you already in the queue of the below item" return render_template('booking.html', obj_str=p_str, obj_all=query_p_all, book_q_from=ibook_from, book_q_to=ibook_to, book_st=False, obj_pid=query_q_fbid.id, obj_ptype=query_q_fbid.product_type, obj_ptitle=query_q_fbid.title, obj_pprice=query_q_fbid.sale_price, session_user_name=username_session, session_first_name=firstname_session, session_last_name=lastname_session, session_email=email_session) elif request.form['inputaddqueue'] == 'No': return redirect(url_for('main')) return redirect(url_for('main'))
def load_products(): # Products product_1 = Product(name="product_1", price=29.99) db.session.add(product_1) product_2 = Product(name="product_2", price=15.00) db.session.add(product_2) product_3 = Product(name="product_3", price=12.34) db.session.add(product_3) db.session.commit() return True
def post(self): """Add new item""" args = product_parser.parse_args() product = Product(product=args['product']) if args['sku']: if db.session.query(Product).filter(Product.sku == args['sku']): product.sku = args['sku'] else: abort(404, message=f'SKU already exists:{args["sku"]}') db.session.add(product) db.session.commit() return product, 201
def add(): if not session.get('logged_in'): return render_template('login.html') if str(request.method) == 'POST': try: vals = request.form.to_dict() files = request.files.getlist("image") for i in range(0, len(files)): file = files[i] ext = file.filename.rsplit('.', 1)[1].lower() if ext in ['png', 'jpg', 'jpeg']: filename = "/static/images/" + base64.urlsafe_b64encode(file.filename) + "." + ext file.save("." + filename) if i == 0: product = Product(vals['name'], vals['description'], filename, 1, 0) db.session.add(product) db.session.commit() db.session.close() img = Image(vals['name'], filename, i) db.session.add(img) db.session.commit() db.session.close() except Exception as err: db.session.rollback() return err.message return render_template('add_product.html')
def patch(self, id): product = Product.query.get_or_404(id) product_dict = request.get_json(force=True) print(product_dict) if 'name' in product_dict and product_dict['name'] is not None: product_name = product_dict['name'] if not Product.is_name_unique(id=0, name=product_name): response = { 'error': 'A product with this name {} already exists'.format( product_name) } return response, HttpStatus.bad_request_400.value product.name = product_name if 'price' in product_dict and product_dict['price'] is not None: product.price = product_dict['price'] if 'description' in product_dict and product_dict[ 'description'] is not None: product.description = product_dict['description'] if 'tags' in product_dict and product_dict['tags'] is not None: product.tags = product_dict['tags'] try: product.update() return self.get(id) except SQLAlchemyError as e: db.session.rollback() response = {"error": str(e)} return response, HttpStatus.bad_request_400.value
def setUp(self): db.session.commit() db.drop_all() db.create_all() testUser = Users(first_name="test", last_name="user", email="*****@*****.**", password=(bcrypt.generate_password_hash("test"))) db.session.add(testUser) testProduct = Product(name="testBoard", style="Fish", volume=55.0, size=9.0, price=500, stock=10, user_id=1) db.session.add(testProduct) testOrder = Orders(user_id=1) db.session.add(testOrder) theOrder = Orders.query.order_by(Orders.id.desc()).first() testOrder_line = Order_line(order_id=theOrder.id, product_id=1, quantity=10, total=2500) db.session.add(testOrder_line) db.session.commit()
def create_product(product_id=None,product_name=None): if product_id is None or len(product_id) <= 3: product_id = random_key(10) existing_products = Product.query(Product.product_id == product_id).fetch(1) if len(existing_products) != 0: import logging logging.error('Product with ID "' + product_id + '" already exists.' ) return make_error(400,'A product with ID ' + product_id + ' already exists, overwriting is forbidden.') product = Product(product_id=product_id) if product_name is not None: product.product_name = product_name product.put() return product.product_id
def th_func(): p_state = Product() print('Testing product') query_state = p_state.query.order_by(p_state.id).all() for index in range(len(query_state)): print(query_state[index].get_id()) bid_status = query_state[index].get_bid_status() if bid_status == "bidding expired": announced = query_state[index].get_sold() print(announced) if not announced: high_bid = query_state[index].get_highest_bid() if not (high_bid is None): user_high = User.query.filter_by( id=high_bid.get_bidder()).first() username_high = user_high.first_name print('username is', username_high) product_high = query_state[index].get_title() print('product is', product_high) socketio.emit('my_response', { 'data': 'Auction Closed', 'cnt': 'for', 'product': product_high, 'wnr': 'And the Winner is', 'winner': username_high }, broadcast=True, namespace='/test')
def search_results(): p_shw = Product() s_name = 'display all items' query_shw = p_shw.query.all() if 'user_id' in session: user = User.query.filter_by(id=session['user_id']).first() username_session = user.username firstname_session = user.first_name lastname_session = user.last_name email_session = user.email if request.method == 'POST': p_shw = Product() s_name = request.form['inputSearch'] s_name = str(s_name) sl_name = s_name.split() print "names:", sl_name query_str_shw = p_shw.query.filter( or_(Product.title.ilike(s_name), Product.title.contains(s_name), Product.product_type.ilike(s_name), Product.product_type.contains(s_name))).all() print "search_str=", s_name print "query_output", query_str_shw if 'user_id' in session: user = User.query.filter_by(id=session['user_id']).first() username_session = user.username firstname_session = user.first_name lastname_session = user.last_name email_session = user.email return render_template('search.html', obj=query_str_shw, session_user_name=username_session, session_first_name=firstname_session, session_last_name=lastname_session, session_email=email_session, obj_src=s_name) return render_template('search.html', obj=query_str_shw, obj_src=s_name) return render_template('search.html', obj=query_shw, session_user_name=username_session, session_first_name=firstname_session, session_last_name=lastname_session, session_email=email_session, obj_src=s_name)
def delete_product(product_id): product = Product.query(Product.product_id == product_id).get() if product is None: return make_error(404,"This product does not exist, so can't be deleted.") product.key.delete() return { 'success': "Product deleted successfully." }
def products(): p_shw = Product() query_shw = p_shw.query.order_by(p_shw.owner_id).all() user = User.query.filter_by(id = session['user_id']).first() username_session = user.username if request.method == 'POST': try: pname = request.form['inputPname'] ptype = request.form['inputPtype'] sbid = request.form['inputSbid'] owner = user.get_id() if pname and ptype and sbid : p = Product( owner_id = owner, title = pname, saleDuration = 3, product_type = ptype, starting_bid = sbid, ) db.session.add(p) db.session.commit() msg = "New Product: %s added." % pname flash(msg) p_suc = Product() query_suc = p_suc.query.order_by(p_suc.owner_id) user = User.query.filter_by(id = session['user_id']).first() username_session = user.username return render_template('products.html',obj=query_suc,session_user_name=username_session) else: flash('Enter all the Required Fields') p_fir = Product() query_fir = p_fir.query.order_by(p_fir.owner_id).all() user = User.query.filter_by(id = session['user_id']).first() username_session = user.username return render_template('products.html',obj=query_fir,session_user_name=username_session) except Exception as e: return json.dumps({'error':str(e)}) return render_template('products.html',obj=query_shw,session_user_name=username_session) return render_template('products.html')
def product(): return Product( id=str(uuid.uuid4()), formatted_price_with_tax='$243.50', name='New product', type='product type', description='New product', currency='USD', slug='new-product', sku='new-product', )
def execute_adding_data(): # print("here") start = datetime.now() print("Started at", start) student_count = Product.query.count() if student_count > 0: print('yes', student_count) else: new_student = Product(name='ABC', location='east', healthy=1) new_student1 = Product(name='ABC2', location='west', healthy=1) new_student2 = Product(name='ABC3', location='north', healthy=1) subjects = [new_student, new_student2, new_student1] print('students_added') for subject in subjects: subject.add() print('subjects added') print('over') ended = datetime.now() print('Ended at', ended) print('Total time taken', ended - start)
def insert_product(): request_payload = json.loads(request.form['data']) product = Product(category_id=request_payload['category_id'], producer_id=request_payload['producer_id'], prod_name=request_payload['prod_name'], price=request_payload['price'], qty=request_payload['qty']) db.session.add(product) db.session.commit() response = jsonify('OK') response.headers.add('Access-Control-Allow-Origin', '*') return response
def test2(): user_budget = request.args.get('budget') products = [] message = "あなたの買うべき物を探しました!" + "\n" + "\n" budget = 100000 category = "" if user_budget: budget = int(user_budget) money = budget if budget < 10000 or budget > 100000: error = Product() error.name = "予算が10万円以内でありません" return render_template("index.html", products=[error], budget=100000) while not products: rand = random.randrange(0, db.session.query(Product.id).count()) products = db.session.query(Product).filter( Product.id == rand, Product.price <= budget).all() budget -= int(products[0].price) while budget > 0: candidate = db.session.query(Product).filter( Product.price <= budget).all() if not candidate: break product = random.choice(candidate) products.append(product) budget -= int(product.price) return render_template("index.html", products=products, budget=budget)
def main(): #return 'Hello ganesh from Flask!' p_shw = Product() query_shw = p_shw.query.order_by(desc(Product.id)).limit(3).all() if 'user_id' in session: user = User.query.filter_by(id=session['user_id']).first() username_session = user.username firstname_session = user.first_name lastname_session = user.last_name email_session = user.email return render_template('index.html', obj=query_shw, session_user_name=username_session, session_first_name=firstname_session, session_last_name=lastname_session, session_email=email_session) return render_template('index.html', obj=query_shw)
def th_func(): p_state = Product() #print('Testing product') query_state = p_state.query.order_by(p_state.id).all() for index in range(len(query_state)): print(query_state[index].get_id()) bid_status = query_state[index].get_bid_status() print('bidding status',bid_status); if bid_status == "bidding expired": announced = query_state[index].get_sold() print('announced is',announced) #engine = pyttsx3.init() #engine.say(announced) #engine.runAndWait() #engine.stop() if not announced: high_bid = query_state[index].get_highest_bid() print('high_bid is', high_bid) if not (high_bid is None): user_high = User.query.filter_by(id = high_bid.get_bidder()).first() print('user_high is', user_high) if not (user_high is None): username_high = user_high.first_name print('username is', username_high) #engine = pyttsx3.init() #engine.say(username_high) #engine.runAndWait() #engine.stop() product_high = query_state[index].get_title() print('product is', product_high) engine = pyttsx3.init() #engine.say(product_high) engine.runAndWait() engine.stop() socketio.emit('my_response', {'data': 'Auction Closed','cnt': 'for', 'product': product_high, 'wnr':'And the Winner is', 'winner':username_high}, broadcast = True,namespace='/test') if(current_user.get_Voice_Enabled()): print(current_user.get_Voice_Enabled()) engine = pyttsx3.init() engine.say("Auction Closed. The Winner is" +username_high) engine.runAndWait() engine.stop()
def submit_board(): form = PostForm() if form.validate_on_submit(): postData = Product(name=form.name.data, size=form.size.data, style=form.style.data, volume=form.volume.data, price=form.price.data, stock=form.stock.data, usersShop=current_user) db.session.add(postData) db.session.commit() return redirect(url_for('home')) else: print(form.errors) return render_template('post.html', title='Post', form=form)
def create_product_submission(farm_id): try: product = Product( name=request.form.get('name'), quantity=request.form.get('quantity'), farm_id=farm_id ) db.session.add(product) db.session.commit() flash('Product ' + request.form.get('name') + ' was successfully listed!') except SQLAlchemyError as e: flash('An error occured. Product ' + request.form.get('name') + ' could not be listed!') db.session.rollback() logging.error(e) abort(400) finally: db.session.close() return redirect(url_for('show_products', farm_id=farm_id))
def save_product(request): if request.method == "POST": id = request.POST.get("id") product = Product() if id: name = request.POST.get("name") cost = request.POST.get("cost") Product.objects.filter(id=id).update(name=name, cost=cost) else: product.name = request.POST.get("name") product.cost = request.POST.get("cost") product.save() return HttpResponseRedirect("/")
def list_products(start_token=''): items_per_page = 100 cursor = Cursor(urlsafe=start_token) products, next_cursor, more = Product.query().order(Product.product_id).fetch_page(items_per_page,start_cursor=cursor) items = [] for product in products: items.append({ 'product_id': product.product_id, 'product_name': product.product_name }) response = { 'kind': api_id + '#productList', 'totalItems': len(products), 'itemsPerPage': items_per_page, 'items': items } if more and next_cursor: response['nextPageToken'] = next_cursor return response
def test_user(): global user_found uid = session['user_id'] p_state = Product() query_state = p_state.query.order_by(p_state.id).all() for index in range(len(query_state)): bid_status = query_state[index].get_bid_status() if bid_status != "bidding expired": usr_act = query_state[index].get_owner() if uid == usr_act: user_found += 1 print(user_found) bids_act = query_state[index].get_all_bids() for indx in range(len(bids_act)): print('bidder:', bids_act[indx].buyer_id) if uid == bids_act[indx].buyer_id: user_found += 1 else: user_found = 1 print('user not found') else: print('no active bids')
def setUp(self): """Setup the test driver and create test users""" print( "--------------------------NEXT-TEST----------------------------------------------" ) chrome_options = Options() chrome_options.binary_location = "/usr/bin/chromium-browser" chrome_options.add_argument("--headless") self.driver = webdriver.Chrome( executable_path= "/home/jamesljeffrey1995/surfBoardShop/chromedriver", chrome_options=chrome_options) self.driver.get("http://*****:*****@test.com", password=(bcrypt.generate_password_hash("test"))) db.session.add(testUser) testProduct = Product(name="testBoard", style="Fish", volume=55.0, size=9.0, price=500, stock=10, user_id=1) db.session.add(testProduct) testOrder = Orders(user_id=1) db.session.add(testOrder) theOrder = Orders.query.order_by(Orders.id.desc()).first() testOrder_line = Order_line(order_id=theOrder.id, product_id=1, quantity=10, total=2500) db.session.add(testOrder_line) db.session.commit()
def post(): name = request.form['name'] print(name) location = request.form['location'] print(location) healthy = request.form['healthy'] print(healthy) item = Product() item.name = name item.healthy = healthy item.location = location db.session.add(item) db.session.commit() response = jsonify({ 'message': 'Satllite added', 'satllite': item.to_json() }) return response
def parse_product_response(dct: Dict) -> Union[None, Product]: product_live_status = 'live' if dct['status'] != product_live_status: return None product_meta = dct['meta'] try: formatted_price_with_tax = product_meta['display_price']['with_tax'][ 'formatted'] except KeyError: formatted_price_with_tax = None try: currency = product_meta['display_price']['with_tax']['currency'] except KeyError: currency = None product_relationships = dct['relationships'] try: main_image_id = product_relationships['main_image']['data']['id'] except KeyError: main_image_id = None product = Product( description=dct['description'], id=dct['id'], type=dct['type'], name=dct['name'], sku=dct['sku'], slug=dct['slug'], formatted_price_with_tax=formatted_price_with_tax, currency=currency, main_image_id=main_image_id, ) return product
def cancel_email(token): try: email_token = cancel_token(token) except: flash('The cancellation link is invalid or has expired.', 'danger') email, bid = email_token.split(',') all_book = Booking() user_bids = User.query.filter(User.email == email).first() booktoc = all_book.query.filter( and_(Booking.buyer_id == user_bids.id, Booking.id == int(bid))).all() if not booktoc: flash('Booking already cancelled. Thank you') else: books_to_del = all_book.query.filter(Booking.id == bid).first() p_all = Product() p_sel = p_all.query.filter( Product.id == books_to_del.product_id).first() bid_title = p_sel.title bq_bk = p_sel.get_highest_queue() bq_all = Bookqueue() #bq_sel = bq_all.query.filter(Bookqueue.p_id == books_to_del.product_id).first() if bq_bk: all_book.query.filter(Booking.id == bid).delete() q_fr = bq_bk.get_booked_from() q_to = bq_bk.get_booked_to() q_uid = bq_bk.get_userid() q_pid = books_to_del.product_id q_m_fr = str(q_fr) q_m_fr = datetime.strftime(q_fr, "%m-%d-%Y %H:%M:%S") q_m_to = str(q_to) q_m_to = datetime.strftime(q_to, "%m-%d-%Y %H:%M:%S") usr_q = User.query.filter(User.id == q_pid).first() b = Booking(bidder=q_uid, product=q_pid, booked_from=q_m_fr, booked_to=q_m_to) db.session.add(b) bq_all.query.filter(Bookqueue.id == bq_bk.id).delete() db.session.commit() email_token = usr_q.email + "," + str(b.id) token = generate_confirmation_token(email_token) cancel_url = url_for('cancel_email', token=token, _external=True) html = render_template('book_cancel.html', cancel_url=cancel_url, obj_ptitle=p_sel.title, obj_pprice=p_sel.sale_price, session_user_name=usr_q.username, session_first_name=usr_q.first_name, session_last_name=usr_q.last_name, session_email=usr_q.email, bookfrom=q_m_fr, bookto=q_m_to) subject = "Your Booking Info" send_email(usr_q.email, subject, html) msg = "You cancelled your Booking with id:", str( bid), "with Title:", str(bid_title) flash(msg) return redirect(url_for('main')) else: all_book.query.filter(Booking.id == bid).delete() db.session.commit() msg = "You have Successfully cancelled your Booking with id:", str( bid), "with Title:", str(bid_title) flash(msg) return redirect(url_for('main')) return redirect(url_for('main'))
def products(): p_shw = Product() query_p_all = p_shw.query.order_by(desc(Product.id)).limit(3).all() user = User.query.filter_by(id=session['user_id']).first() username_session = user.username firstname_session = user.first_name lastname_session = user.last_name email_session = user.email if request.method == 'POST': try: pname = request.form['inputPname'] ptype = request.form['inputPtype'] pdesc = request.form['inputPdesc'] sprice = request.form['inputSprice'] ppic = request.files['inputPpic'] paddr = user.user_addr + "," + user.user_city owner = user.get_id() print "saleprice=", sprice if pname and ptype and sprice: p = Product(owner_id=owner, title=pname, sale_price=sprice, product_type=ptype, product_desc=pdesc, product_addr=paddr) db.session.add(p) db.session.commit() p_suc = Product() query_suc = p_suc.query.filter( and_((Product.title == pname), (Product.sale_price == sprice))).all() user = User.query.filter_by(id=session['user_id']).first() username_session = user.username firstname_session = user.first_name lastname_session = user.last_name email_session = user.email query_p_all = p_suc.query.order_by(desc( Product.id)).limit(3).all() if ppic: ppic_fname = secure_filename(ppic.filename) pic_name = 'img_' + str(p.id) + '.jpg' print "if case filename", ppic_fname, pic_name ppic.save(ppic_fname) os.rename(ppic_fname, pic_name) print "if case filename", ppic_fname, pic_name dst_dir = os.path.join(os.curdir, "static/img/") src_file = os.path.join(os.curdir, pic_name) shutil.move(src_file, dst_dir) print "if case filename", pic_name, src_file else: ppic_fname = 'img.jpg' pic_name = 'img_' + str(p.id) + '.jpg' os.rename(ppic_fname, pic_name) cwd = os.getcwd() dst_dir = os.path.join(cwd, application.config['IMG_FOLDER']) src_file = os.path.join(os.curdir, pic_name) shutil.copy(src_file, dst_dir) os.rename(pic_name, 'img.jpg') print "else case filename", pic_name return render_template('products.html', obj=query_suc, obj_all=query_p_all, session_user_name=username_session, session_first_name=firstname_session, session_last_name=lastname_session, session_email=email_session) else: flash('Enter all the Required Fields') user = User.query.filter_by(id=session['user_id']).first() username_session = user.username firstname_session = user.first_name lastname_session = user.last_name email_session = user.email p_fail = Product() query_p_all = p_fail.query.order_by(desc( Product.id)).limit(3).all() return render_template('products.html', obj_all=query_p_all, session_user_name=username_session, session_first_name=firstname_session, session_last_name=lastname_session, session_email=email_session) except Exception as e: return json.dumps({'error': str(e)}) return render_template('products.html', obj_all=query_p_all, session_user_name=username_session, session_first_name=firstname_session, session_last_name=lastname_session, session_email=email_session)
def save_products(self): """Save products and categories in Database.""" api_class = Api() products_and_categories_from_api = api_class.download_products() if products_and_categories_from_api is not None: print(" ✅ Les produits ont été téléchargé avec succès depuis l'API") else: print(" ❌ -> Les produits n'ont pas pu être téléchargés depuis l'API") for product in products_and_categories_from_api: name = product.get("product_name_fr")[:150].strip().lower().capitalize() brands = product.get("brands")[:150].strip().lower().capitalize() grade = product.get("nutriscore_grade")[0].upper() barcode = product.get("code")[:13].strip() url = product.get("url") picture = product.get("image_url") small_picture = product.get("image_small_url") categories = [ name.strip().lower().capitalize() for name in product["categories"].split(",") ] selected_nutriments = [ "energy_100g", "sugars_100g", "fat_100g", "salt_100g", ] nutriments_dict = {} for nutriment in selected_nutriments: nutriment_value = product.get("nutriments").get(nutriment) if isinstance(nutriment_value, float) is True: value = nutriment_value else: value = 0 nutriments_dict[nutriment] = value product_instance = Product( name=name, brand=brands, barcode=barcode, score=grade, url=url, image_url=picture, small_image_url=small_picture, kcal_100g=nutriments_dict.get("energy_100g"), sugar_100g=nutriments_dict.get("sugars_100g"), salt_100g=nutriments_dict.get("salt_100g"), fat_100g=nutriments_dict.get("fat_100g"), ) try: product_instance.save() saved_categories = [] for category in categories: category_instance = Category(name=category) if category not in saved_categories: saved_categories.append(category) try: category_instance.save() except IntegrityError: category_instance = Category.objects.get(name=category) # Link products to categories product_instance.categories.add(category_instance) product_instance.save() except IntegrityError: continue print("😎 -> LA BASE DE DONNÉES EST COMPLÉTÉE ! <- 😎")
def book(): p_bids = Product() user_bids = User.query.filter_by(id=session['user_id']).first() query_p_all = p_bids.query.order_by(desc(Product.id)).limit(3).all() username_session = user_bids.username if request.method == 'POST': try: bpid = request.form['bookId'] bfrom = request.form['date1'] bto = request.form['date2'] user_book = User.query.filter_by(id=session['user_id']).first() owner = user_book.get_id() test_bfrom = str(bfrom) test_bto = str(bto) bfrom = test_bfrom.replace("/", "-") bfrom = bfrom + " 00:00:00" bto = test_bto.replace("/", "-") bto = bto + " 00:00:00" bk_all = Booking() bk_list = bk_all.query.filter(Booking.product_id == bpid).all() if bk_list: for index in range(len(bk_list)): booked_from = bk_list[index].get_booked_from() booked_to = bk_list[index].get_booked_to() res_dt = verify_date(booked_from, booked_to, bfrom, bto) print "Result of verify_date:", res_dt if not res_dt: delta = datetime.strptime( bto, "%m-%d-%Y %H:%M:%S") - datetime.strptime( bfrom, "%m-%d-%Y %H:%M:%S") al_date = bk_list[index].getmaxtodate() delta_1 = timedelta(days=1) al_date_fm = al_date.booked_to + delta_1 al_date_to = al_date_fm + delta p_al_bid = Product() query_al_fbid = p_al_bid.query.filter_by( id=bpid).first() user = User.query.filter_by( id=session['user_id']).first() username_session = user.username firstname_session = user.first_name lastname_session = user.last_name email_session = user.email if query_al_fbid: print "inside query_al_fbid:", query_al_fbid.product_type query_sim = p_al_bid.query.filter( Product.product_type == query_al_fbid.product_type).all() print "inside query_al_fbid:", query_al_fbid.product_type if query_sim: print "inside query_al_fbid:", query_al_fbid.product_type return render_template( 'booking.html', obj_1=query_sim, bookfrom=bfrom, bookto=bto, ibookpid=bpid, bookalfrom=al_date_fm, bookalto=al_date_to, book_st=False, obj_pid=query_al_fbid.id, obj_ptype=query_al_fbid.product_type, obj_ptitle=query_al_fbid.title, obj_pprice=query_al_fbid.sale_price, session_user_name=username_session, session_first_name=firstname_session, session_last_name=lastname_session, session_email=email_session) else: query_p_all = p_al_bid.query.order_by( desc(Product.id)).limit(3).all() return render_template( 'booking.html', obj_all=query_all, bookfrom=bfrom, bookto=bto, ibookpid=bpid, bookalfrom=al_date_fm, bookalto=al_date_to, book_st=False, obj_pid=query_al_fbid.id, obj_ptype=query_al_fbid.product_type, obj_ptitle=query_al_fbid.title, obj_pprice=query_al_fbid.sale_price, session_user_name=username_session, session_first_name=firstname_session, session_last_name=lastname_session, session_email=email_session) return render_template( 'booking.html', bookfrom=bfrom, bookto=bto, ibookpid=bpid, bookalfrom=al_date_fm, bookalto=al_date_to, book_st=False, obj_pid=query_al_fbid.id, obj_ptype=query_al_fbid.product_type, obj_ptitle=query_al_fbid.title, obj_pprice=query_al_fbid.sale_price, session_user_name=username_session, session_first_name=firstname_session, session_last_name=lastname_session, session_email=email_session) print "product id:", bpid if bpid and bfrom and bto: b = Booking(bidder=owner, product=bpid, booked_from=bfrom, booked_to=bto) db.session.add(b) db.session.commit() p_fbid = Product() query_fbid = p_fbid.query.filter_by(id=bpid).first() user = User.query.filter_by(id=session['user_id']).first() username_session = user.username firstname_session = user.first_name lastname_session = user.last_name email_session = user.email email_token = email_session + "," + str(b.id) token = generate_confirmation_token(email_token) cancel_url = url_for('cancel_email', token=token, _external=True) html = render_template('book_cancel.html', cancel_url=cancel_url, obj_ptitle=query_fbid.title, obj_pprice=query_fbid.sale_price, session_user_name=username_session, session_first_name=firstname_session, session_last_name=lastname_session, session_email=email_session, bookfrom=bfrom, bookto=bto) subject = "Your Booking Info" send_email(user.email, subject, html) return render_template('booking.html', bookfrom=bfrom, bookto=bto, book_st=True, obj_pid=query_fbid.id, obj_ptitle=query_fbid.title, obj_pprice=query_fbid.sale_price, obj_ptype=query_fbid.product_type, session_user_name=username_session, session_first_name=firstname_session, session_last_name=lastname_session, session_email=email_session) else: p_sid = Product() query_sid = p_sid.query.filter_by(id=bpid).first() user = User.query.filter_by(id=session['user_id']).first() username_session = user.username firstname_session = user.first_name lastname_session = user.last_name email_session = user.email return render_template('booking.html', obj_pid=query_fbid.id, obj_ptitle=query_fbid.title, obj_pprice=query_fbid.sale_price, obj_ptype=query_fbid.product_type, session_user_name=username_session, session_first_name=firstname_session, session_last_name=lastname_session, session_email=email_session) except Exception as e: return json.dumps({'error': str(e)}) return redirect(url_for('main'))
try: from application import db from application.models import Product, User, Image import yaml with open("db.yml") as db_file: db_entries = yaml.safe_load(db_file) db.create_all() for user in db_entries["users"]: usr = User(user["username"], user["password_hash"]) db.session.add(usr) db.session.commit() for project in db_entries["projects"]: proj = Product(project["name"], project["description"], project["default_image"], 1, 0) db.session.add(proj) db.session.commit() for i in range(0, len(project["images"])): img = Image(project['name'], project["images"][i], i) db.session.add(img) db.session.commit() db.session.close() except Exception as err: errors.append(err.message) # EB looks for an 'application' callable by default. application = Flask(__name__) # config application.config.update(
def list_products(): products = Product.all().get() return products