def get_products(db, paras): listObj = { "items": [], "total": 0, } type = paras["type"] cond = "WHERE 1=1 " if type: cond += "AND P_Type='%s' " % type state = paras["state"] if state: cond += "AND P_State='%s' " % state cond += "ORDER BY P_CreateTime " ret = db.select(TB_PRODUCT, cond=cond) if ret == -1: ERROR("get user list error") return (DB_ERR, None) for dur in db.cur: obj = dbmysql.row_to_dict(TB_PRODUCT, dur) product = Product(db, dbObj=obj) product.loadFromObj() listObj["items"].append(product.toObj()) listObj["items"].sort(key=lambda x: x["infoObj"]["id"]) listObj["total"] = len(listObj["items"]) return (OCT_SUCCESS, listObj)
def process(self, request, session): _id = request.values.get('id') productObj = Product() prodDetail = productObj.find({'_id': ObjectId(_id)}) if (prodDetail.count() != 1): return abort(404) log, u = checkLogin(session) return render_template('product.html', m=prodDetail[0], log=log, u=u)
def setUpClass(self): """ Method to setup global values needed for all tests """ self.guitar = Product('Electric Guitar', 3.50, 'Fun way to make music.') self.shampoo = Product("Coconut Oil Shampoo", 7.99, "silky smoothe hair treatment shampoo")
def search_prod(prod): product = Product() products = product.filterByName(prod) ret_prods = [] if products: for p in products: img = str(b64encode(p[3]).decode("utf-8")) ret_prods.append({"id": p[0], "descricao": p[1], "valor": str(p[2]), "imagem": img}) return jsonify(ret_prods)
def process(self, request, session): query = request.values.get('query') productObj = Product() prodList = productObj.findAll(query) log, u = checkLogin(session) return render_template('search.html', query=query, m=prodList, log=log, u=u)
def post(self): args = parser.parse_args() product = Product(name=args['name'], description=args['description'], preco=args['preco'], store_id=args['store_id'], label=args['label']) db.add(product) db.commit() return product.serialize(), 201
def products(self, submit): product = Product() products = product.get_all_products(with_quantity=True) res = '' for elem in products: # res = res.join(f"<li>{i}</li>" for i in elem)+"<br>" res = res + "<li> ID: " + str(elem[0]) + "</li>" res = res + "<li> Product name: " + str(elem[1]) + "</li>" res = res + "<li> Price: " + str(elem[2]) + "</li>" res = res + "<li> Article: " + str(elem[3]) + "</li>" res = res + "<li> Quantity: " + str(elem[4]) + "</li> <br>" return f"""
def index(): product = Product() desc = request.args.get('descricao', '') if desc: products = product.getByDesc(desc) else: products = product.getAll() images = [] for product in products: images.append(b64encode(product[3]).decode("utf-8")) return render_template('product.html', products=products, images=images, desc=desc), 200
def add(): form = ProductForm() title = 'Cadastrar Produto' if form.validate_on_submit(): image = request.files.get('imagem') if image: product = Product( form.descricao.data, form.valor.data, image.read() ) ret = product.insert() flash(ret, 'info') return redirect(url_for('product.index')) return render_template('product_form.html', form=form, title=title, mode='add'), 200
def applyDiscountOnProduct(self, productBody): foundProduct = self.productDiscountRepository.checkIfProductIsInDatabase(productBody['Id']) if foundProduct: return self.productDiscountRepository.updateProductDiscount(productBody['Id'], productBody) type = productBody['Type'] ValidFrom = datetime.now() ValidTo = datetime.now() # Generating the percentage based on the how much was the product sold if type == 'mostBought': discountPercentage = 10 ValidTo = ValidFrom + timedelta(days=30) elif type == 'leastBought': discountPercentage = 20 ValidTo = ValidFrom + timedelta(days=30) else: return {'error': 'Type of product discount can only be mostBought or leastBought. {} is illegal type.'.format(type)}, 400 timesBought = 0 newProduct = Product(Id=productBody['Id'], TimesBought=timesBought, ValidFrom=ValidFrom, ValidTo=ValidTo, Type=type, DiscountPercentage=discountPercentage) return self.productDiscountRepository.applyDiscountOnProduct(newProduct=newProduct)
def add_product_1_0(): if not request.json or 'barcode' not in request.json\ or 'units' not in request.json or 'price' not in request.json\ or 'name' not in request.json: abort(400) if not request.json['barcode'] or not request.json['name']\ or not request.json['units'] or not request.json['price']: abort(400) if (logger.log_op(request.json)): m = MasterList.query.filter_by(barcode=request.json['barcode']).first() if m is not None: abort(409, {"message": "Producto existente"}) m = ProductsMasterlist(request.json['barcode'], request.json['name'], request.json['price']) db_session.add(m) db_session.commit() p = Product(request.json['barcode'], request.json['units'], 1) db_session.add(p) db_session.commit() prod = ProductStore.query.filter_by( barcode=request.json['barcode']).filter_by(storeid=1).first() return make_response(jsonify({"mobilerp": prod.serialize}), 200) else: return make_response( jsonify({'mobilerp': 'Operacion duplicada, saltando'}), 428)
def show(product_id): schema = ProductSchema() product = Product.get(id=product_id) if not product: abort(400) return schema.dumps(product)
def buy_fund(): jongmok = input('종목명?') yongdo = input('용도?') while True: price = input('가격?') if price.isdigit(): break while True: yang = input('개수는?') if yang.isdigit(): break dec = input('기타 추가 설명을 입력해주세요.') obj = Product(jongmok, yongdo, yang, dec, price) obj.print_obj() bot.send_msg(obj.make_str())
def edit(id): title = 'Editar Produto' product = Product() ret = product.get(id) if not product.id: flash(ret, 'info') return redirect(url_for('product.index')) image = b64encode(product.imagem).decode("utf-8") if request.form: form = ProductForm() product.descricao = form.descricao.data product.valor = form.valor.data if form.imagem_edicao.data.filename != '': image_edit = request.files.get('imagem_edicao') product.imagem = image_edit.read() else: image_edit = product.imagem else: form = ProductForm() form.descricao.data = product.descricao form.valor.data = product.valor form.imagem.validators = [] if form.validate_on_submit(): ret = product.update() flash(ret, 'info') return redirect(url_for('product.edit', id=product.id)) return render_template('product_form.html', form=form, title=title, mode='edit', image=image, productId=product.id), 200
def updateHelper(barcode, units, storeid): p = Product.query.filter_by(storeid=storeid, barcode=barcode).first() if p is None: p = Product(barcode, 0, storeid) u = p.units + units db_session.add(p) db_session.commit() return "UPDATE product set units={0} where barcode='{1}' and storeid={2}"\ .format(u, barcode, storeid)
def delete(id): product = Product() ret = product.get(id) if not product.id: flash(ret, 'info') return redirect(url_for('product.index')) order = OrderProduct() has = order.hasByProduct(id) if has: flash('O produto não pode ser deletado pois ele já está relacionado à algum pedido.', 'info') return redirect(url_for('product.index')) if request.method == 'POST': ret = product.delete() flash(ret, 'info') return redirect(url_for('product.index')) title = 'Deseja realmente deletar o produto ' + str(product.id) + '?' return render_template('product_delete.html', productId=id, title=title), 200
def product_create(user, storeId): product_fields = product_schema.load(request.json) product = Product.query.filter_by(title=product_fields["title"]).first() if product: return abort(400, description="Title already in use") new_product = Product() new_product.title = product_fields["title"] new_product.price = product_fields["price"] new_product.store_id = storeId store = Store.query.filter_by(id=storeId, user_id=user.id).first() if not store: return abort(400, description="Incorrect storeID in URL") store.product.append(new_product) db.session.commit() return jsonify(product_schema.dump(new_product))
def post(self): self.name = request.json['name'] self.description = request.json['description'] self.price = request.json['price'] self.qty = request.json['qty'] self.new_product = Product(self.name, self.description, self.price, self.qty) db.session.add(self.new_product) db.session.commit() return product_schema.jsonify(self.new_product)
def delete(product_id): product = Product.get(id=product_id) if not product: abort(404) product.delete() db.commit() return '', 204
def add_product(db, paras): product = Product(db, name=paras["name"]) product.type = paras["type"] product.desc = paras["desc"] infoObj = { "id": paras["code"], "type": paras["type"], "name": paras["name"], "provider": paras["provider"], "price": paras["price"], "costPrice": paras["costPrice"], "desc": paras["desc"], "model": paras["model"], "code": paras["code"] } if paras["frequency"]: infoObj["frequency"] = paras["frequency"] if paras["cores"]: infoObj["cores"] = paras["cores"] if paras["threads"]: infoObj["threads"] = paras["threads"] if paras["capacity"]: infoObj["capacity"] = paras["capacity"] product.infoObj = infoObj ret = product.add() return ret, None
async def createProduct(request): try: body = await request.json() except Exception as e: raise ClientException('Invalid body') # every field may be null productToCreate = Product(name=body.get("name", None), description=body.get("description", None), properties=body.get("properties", None)) await productToCreate.commit() return web.json_response({'id': str(productToCreate.id)})
def newProduct(): if not request.json or 'barcode' not in request.json\ or 'units' not in request.json or 'price' not in request.json\ or 'name' not in request.json: abort(400) if request.json['barcode'] is '' or request.json['name'] is ''\ or request.json['units'] is '' or request.json['price'] is '': abort(401) p = Product(request.json['barcode'], request.json['name'], request.json['units'], request.json['price']) db_session.add(p) db_session.commit() return make_response(jsonify({'mobilerp': [p.serialize]}), 200)
def get(self): user_info = self.session['index_user'].to_json() wish_list = [] try: wish_all = session.query(Collection).filter_by( UserID=user_info['UserID']).all() for wish in wish_all: wish_dict = wish.to_json() Product = getProductByPidFirst(wish_dict['ProductID']) wish_dict['product'] = Product.to_json() wish_list.append(wish_dict) except Exception, e: print e pass
def create(): schema = ProductSchema() try: data = schema.load(request.get_json()) product = Product(**data) db.commit() except ValidationError as err: #if the Validation fails, send back 422 response return jsonify({ 'message': 'Validation failed', 'errors': err.messages }), 422 return schema.dumps(product), 201
async def getProductByFilter(request): try: body = await request.json() except Exception as e: raise ClientException('Invalid body') name = body.get('name', None) properties = body.get('properties', None) filterOption = {} if name is not None: filterOption['name'] = name if properties is not None and isinstance(properties, dict): for key, value in properties.items(): filterOption[f'properties.{key}'] = value prodList = [p.toSmallDict() async for p in Product.find(filterOption)] return web.json_response(prodList)
def getCategorySpecificRecords(node, name, recordCount): numCalls = int(math.ceil(float(recordCount)/pageSize)) products = [] #iterate through all pages and append the product data for specific category for currentPage in range(1,numCalls+1): curr_url ='https://www.sephora.com/api/catalog/search?country_switch=ca&type=keyword&q=sale&icid2=meganav_sale_top_nav_link%3fpageSize=-1¤tPage=' + str(currentPage) + '&content=true&includeRegionsMap=true&page=60¤tPage=' + str(currentPage) s_url = curr_url + "&node=" + str(node) req = Request(url=s_url, headers=headers) res = urlopen(req).read().decode() productData = json.loads(res) for x in productData["products"]: salePriceExists = x["currentSku"] if "salePrice" in salePriceExists: p = Product(x["brandName"],x["productName"], x["heroImage"], x["productId"], x["rating"], x["currentSku"]["listPrice"], x["currentSku"]["salePrice"], x["currentSku"]["isLimitedEdition"], x["currentSku"]["isLimitedTimeOffer"]) products.append(p) return products
def test_can_get_all_saved_product(self): """ Method to test if all saved product can be retrieved with the attibutes of id, price, name """ prodData = ProductData() prodData.save_product(self.guitar) data = prodData.get_all_products() data_index_1 = len(data) self.Electric = Product('Electric Guitar', 5.50, 'Fun way to make music.') prodData.save_product(self.Electric) data = prodData.get_all_products() data_index_2 = len(data) self.assertEqual(data_index_2, data_index_1 + 1) self.assertIn((data_index_2, 5.50, 'Electric Guitar'), data)
def update(product_id): schema = ProductSchema() product = Product.get(id=product_id) if not product: abort(400) try: data = schema.load(request.get_json()) product.set(**data) db.commit() except ValidationError as err: return jsonify({ 'message': 'Validation failed', 'errors': err.messages }), 422 return schema.dumps(product)
async def getProducts( self, productFilter: 'ProductRepository.Filter', currency: str = 'USD' # yes, it is just hardcoded ) -> List[Product]: multiplier = await self.getCurrencyMultiplier(currency) if multiplier is None: raise Exception(f'No multiplier for currecncy {currency}') productFilter.applyMultiplier(multiplier) sql = Query.from_(products) \ .select( products.id, products.name, products.picture, (products.price_dollar * multiplier).as_('price') ).where(productFilter.getCriterion()) \ .limit(productFilter.limit).offset(productFilter.offset) result = await databaseClient.query(sql.get_sql()) return [ Product( id = row[0], name = row[1], picture = row[2], price = row[3].normalize() ) for row in result ]
def post(self): # 新增商品 try: # 获取前端传来的参数 data = json.loads(self.get_argument('data')) if data['IsHot'] == '1': data['IsHot'] = True else: data['IsHot'] = False if data['IsNew'] == '1': data['IsNew'] = True else: data['IsNew'] = False pro = Product(**data) session.add(pro) session.commit() self.write_json(pro.ProductID, code=1) except Exception, e: # 事务 print e session.rollback() self.write_json("failed", code=0)