def setUp(self): self.BaseSetUp() self.fake = Faker() self.mock_rating = ProductRating( id=1, created_at=datetime.now(), updated_at=datetime.now(), product_id=1, user_id=1, rating=1.2, channel='web' ) self.mock_product_with_dependants = Product( id=1, created_at=datetime.now(), updated_at=datetime.now(), is_deleted=False, name=self.fake.name(), description=self.fake.name(), price=34.5, discounted_price=23.5, display=20, sold=10, is_active=True, ratings=[self.mock_rating, ], ) self.mock_product = Product( id=1, created_at=datetime.now(), updated_at=datetime.now(), is_deleted=False, name=self.fake.name(), description=self.fake.name(), price=34.5, discounted_price=23.5, display=20, sold=10, is_active=True ) self.mock_deleted_product = Product( id=1, created_at=datetime.now(), updated_at=datetime.now(), is_deleted=True, name=self.fake.name(), description=self.fake.name(), price=34.5, discounted_price=23.5, display=20, sold=10, is_active=True )
def addGoods(self, goods): different_count = 0 same_count = 0 if len(goods) > 0: for item in goods: items = Product.query.filter_by( productId=item['productId']).order_by( Product.create_time.desc()) if items is not None and (items.count() > 0) and items.first( ) and (items.first().price == item['price']): same_count += 1 else: different_count += 1 product_model = Product() if items.count() > 0: first = items.first() first.latest = False print('上期价格:', first.price, '本期价格:', item['price']) item['compare'] = round( (float(item['price']) - float(first.price)) / float(first.price), 4) item['latest'] = True else: item['compare'] = 1 item['latest'] = True product_model.set_attrs(item) db.session.add(product_model) db.session.commit() return same_count, different_count
def post(self): form = BiddingForm() print('hello') if form.validate_on_submit(): bid = Bid(per_price=form.per_price.data, low_price=form.low_price.data, now_price=form.low_price.data, due_time=form.due_time.data) product = Product(seller_id=current_user.id, name=form.name.data, price=form.price.data, detail=form.detail.data, bid = bid, image="product." + form.image.data.filename[-3:].lower(), bidding=True, status=0) product.save() image_path = os.path.join(os.getcwd(), 'app/static/image', str(product.id)) os.makedirs(image_path) form.image.data.save(os.path.join(image_path, product.image)) return redirect(url_for('user.profile')) return render_template('user/selling/bidding.html', form=form)
def test_create_product_already_exists(self): product = Product( product_name="python_v3_7", release_info_url="https://www.python.org/downloads/", xpath_version_number='//p[@class="download-buttons"]/a/text()', xpath_download_url='//p[@class="download-buttons"]/a/@href', ) db.session.add(product) db.session.commit() with self.client: jwt_auth = create_admin_user_and_sign_in(self) create_product_response = create_product( self, "python_v3_7", "https://www.python.org/downloads/", '//p[@class="download-buttons"]/a/text()', '//p[@class="download-buttons"]/a/@href', jwt_auth, ) create_product_data = create_product_response.get_json() self.assertEqual(create_product_data["status"], "fail") self.assertEqual( create_product_data["message"], "Product name: python_v3_7 already exists, must be unique.", ) self.assertEqual(create_product_response.content_type, "application/json") self.assertEqual(create_product_response.status_code, HTTPStatus.CONFLICT)
def __init__(self): """Init.""" self.view: ViewSaveSubstitute = ViewSaveSubstitute() self.product: Product = Product() self.substitutes = self.product.retrieve_substitute() self.indexes = [str(index) for index in range(1, len(self.substitutes) + 1)] self.possible_commands = ["back-to-menu", s.QUIT_APP]
def post(self): form = NormalForm() categories = Category.objects() if form.validate_on_submit(): product = Product(seller_id=current_user.id, name=form.name.data, price=form.price.data, detail=form.detail.data, image="product." + form.image.data.filename.split(".")[1].lower(), categories=request.form.getlist("categories"), bidding=False, status=0) product.save() image_path = os.path.join(os.getcwd(), 'app/static/image', str(product.id)) os.makedirs(image_path) form.image.data.save(os.path.join(image_path, product.image)) return redirect(url_for('user.profile')) return render_template('user/selling/normal.html', form=form, categories=categories)
def __call__(self, request, category_name): if request.is_json: data = request.get_json() owner_email = data['owner_email'] product_name = data['name'] owner = User.get_by_email(owner_email) category = Category.get_category_by_name(category_name) if (owner and category): if Product.is_product_on_category(Category, product_name, category_name): new_product = Product(name=product_name, price=data['price'], units=data['units'], owner=owner, category=category) return new_product.save() else: return response_message( False, f"Product {product_name} already exists on {category_name}" ) else: return response_message(False, "Owner or category doesn't exist") else: return response_message( False, "The request payload is not in JSON format")
def get(self): apiResponse = requests.get('http://sigmatest.sigmastorage.online/') productDic = productSchema.load(apiResponse.json()) inquiredProduct = Product(productDic['id'], productDic['name'], productDic['image'], productDic['price'], productDic['tax']) oldProduct = Product.get_by_id(inquiredProduct.id) if (oldProduct): if (not validateProductEquals(inquiredProduct, oldProduct)): oldProduct.name = inquiredProduct.name oldProduct.image = inquiredProduct.image oldProduct.price = inquiredProduct.price oldProduct.tax = inquiredProduct.tax oldProduct.update() else: inquiredProduct.save() productResponse = ProductResponse(inquiredProduct.id, inquiredProduct.name, inquiredProduct.image, inquiredProduct.price, inquiredProduct.tax) productResponse.tax = calculateTax(inquiredProduct) productResponse.discount = calculateDiscount(inquiredProduct) return productSchema.dump(productResponse)
def add(item: ProductCreate): product = Product(uuid.uuid4(), item.name, item.price, item.active) if product.is_invalid: return GenericResponse(False, concatenate.execute(product.notifications)) repository.add(product) return GenericResponse(True, 'Cadastrado com sucesso!')
def test_one_product_object_created_successfully(self): "Tests if one product can be added" product = Product("Sugar", 2000) self.assertListEqual([None, "Sugar", 2000, 1], [ product.product_id, product.product_name, product.product_price, product.product_count ])
def createProduct(): productForm = ProductForm() providerForm = ProviderForm() choices = [(p.id, p.trading_name) for p in Provider.query.order_by('trading_name')] choices.insert(0, ('0', 'Selecione')) productForm.provider.choices = choices providers = Provider.query.all() if productForm.validate_on_submit(): provider_id = None if "0" != productForm.provider.data: provider_id = productForm.provider.data product = Product(productForm.product_name.data, productForm.serial_number.data, productForm.branch.data, productForm.model.data, productForm.quantity.data, productForm.category.data, productForm.description.data, productForm.coast.data, productForm.status.data, provider_id) db.session.add(product) db.session.commit() flash('Produto criado com sucesso!', 'success') return redirect(url_for('indexProduct')) return render_template('product/form.html', productForm=productForm, providerForm=providerForm, providers=providers)
def create_prods(data: List[ProductPostObj], db: Session = Depends(get_db)): for i in data: product = Product(**dict(i)) db.add(product) db.commit() db.refresh(product) return {"res": "created successfully"}
def post(self): form = PublishForm() if form.validate_on_submit(): product = Product(seller_id=current_user.id, name=form.name.data, price=form.price.data, detail=form.detail.data, image="product." + form.image.data.filename[-3:].lower(), auction=bool(form.auction.data), status=0) product.save() image_path = os.path.join(os.getcwd(), 'app/static/image', str(product.id)) os.makedirs(image_path) form.image.data.save(os.path.join(image_path, product.image)) if product.auction == True: bid = Bid(per_price=form.per_price.data, low_price=form.low_price.data, due_time=form.due_time.data) product.bid = bid product.save() return redirect(url_for('user.profile')) return render_template('user/selling/publish.html', form=form)
def extract(): if request.method == 'POST': product_id = request.form.get('product_id') product = Product(product_id) product.extract_product() product.save_to_json() return redirect(url_for('opinions', product_id=product_id)) return render_template('extract.html.jinja')
def __init__(self, category_index: int): """Initialise.""" category = Category().get_categories()[category_index] self.product_model = Product() self.products = self.product_model.get_products(category) self.view = ProductView(self.products)
def extract(): if request.method == "POST": product_id = request.form.get("product_id") product = Product(product_id) product.extract_product() product.save_to_json() return redirect(url_for("opinions", product_id=product_id)) return render_template("extract.html.jinja")
def add_product(self, product_name, quantity, unit_price): # create a new product entry new_product = Product(product_name=product_name, quantity=quantity, unit_price=unit_price) self.dbcon.add_new_product(product=new_product.product_name, quantity=new_product.quantity, unit_price=new_product.unit_price) return True
def opinions(product_id): print(product_id) product = Product(product_id) info = {} with open(f"app/info/{product_id}_info.json", "r", encoding="UTF-8") as fp: r = json.load(fp) info = r print(", ".join(op.opinion_id for op in product.opinions)) product.read_from_json() return render_template('opinions.html.jinja', info=info, product=str(product))
def test_it_can_be_instantiated(self): """ Test Instantiation """ product = Product(id=1, name="Test", price=1.0, description="Test Description") self.assertEqual(product.id, 1) self.assertEqual(product.name, "Test") self.assertEqual(product.price, 1.0) self.assertEqual(product.description, "Test Description")
def __init__(self): """Init.""" self.view: ViewDeletedSubstitutesConfirm = ViewDeletedSubstitutesConfirm( ) self.product: Product = Product() self.indexes = [ str(index) for index in range(1, len(self.view.menu_choices) + 1) ] self.possible_commands = ["back-to-menu", s.QUIT_APP]
def test_serialize_a_product(self): product = Product(id=1, name="Test", price=1.0, description="Test Description") product = product.serialize() self.assertEqual(product['id'], 1) self.assertEqual(product['name'], "Test") self.assertEqual(product['price'], 1.0) self.assertEqual(product['description'], "Test Description")
def extract(): if request.method == 'POST': product_id = request.form.get('product_id') product = Product(product_id) product.extract_product() if product.product_name == "empty_product_name": return render_template('extractError.html.jinja') product.save_to_json() product.create_json_stats() return redirect(url_for('opinions', product_id=product_id)) return render_template('extract.html.jinja')
def extract(): if request.method == 'POST': productId = request.form.get('productId') product = Product(productId) product.extractName() if product.name is not None: product.extractProduct() product.exportProduct() return redirect(url_for('product', productId=productId)) error = 'Podana wartość nie jest poprawnym kodem produktu' return render_template('extract.html.jinja', error=error) return render_template('extract.html.jinja')
def test_ProductPutService_can_put_name_and_price(): session = MagicMock() service = ProductPutService(data={ 'name': 'White trainer', 'price': '50.00' }, product=Product(name='Black trainer', price='55.00'), db_session=session) product = service.put() assert product.name == 'White trainer' assert product.price == '50.00'
def test_ProductPutService_can_put_price(): session = MagicMock() service = ProductPutService(data={ 'name': 'Lavender heart', 'price': '10.25' }, product=Product(name='Lavender heart', price='9.25'), db_session=session) product = service.put() assert product.name == 'Lavender heart' assert product.price == '10.25'
def __init__(self): """Init.""" self.category: Category = Category() self.product: Product = Product() self.del_substitute = True self.menu_choices = [ "Rechercher un aliment à remplacer", "Retrouver mes aliments substitués.", ] self.back = f'{colored(self.justify("m", 1), "yellow")} : {s.BACK}' self.quit = f'\n{colored(self.justify("q", 1), "yellow")} : {s.QUIT}\n' self.msg_choice = f"\n\n{self.justify(s.MSG_CHOICE, 3)}" self.select_category = colored(self.justify(s.SELECT_CATEGORY, 2), "cyan") self.select_product = colored(self.justify(s.SELECT_PRODUCT, 2), "cyan") self.product = self.justify(s.PRODUCT, 1) self.brand = self.justify(s.BRAND, 1) self.stores = self.justify(s.STORES, 1) self.url = self.justify(s.URL, 1) self.nutriscore = self.justify(s.NUTRISCORE, 1) self.msg_error = colored(self.justify(s.MSG_ERROR, 3), "red") self.no_substitute = colored(self.justify(s.NO_SUBSTITUTE, 3), "red") self.save_confirm = colored(self.justify(s.SAVE_CONFIRM, 3), "green") self.saved_products = self.justify(s.SAVED_PRODUCTS, 2) self.substituted_detail = colored( self.justify(s.SUBSTITUTED_DETAIL, 2), "cyan") self.substitute_detail = colored(self.justify(s.SUBSTITUTE_DETAIL, 2), "cyan") self.confirm_title = self.justify(s.CONFIRM_TITLE, 3) self.you_have_selected = colored(self.justify(s.YOU_HAVE_SELECTED, 3), "cyan") self.del_alert = self.justify(colored(s.DEL_ALERT, "red"), 3) self.othr_cmd = self.centerize(s.OTHER_COMMANDS, s.CHAR_LENGHT) self.app_title = self.centerize(s.APP_TITLE, s.CHAR_LENGHT) self.head = self.justify( f"{s.DSH * 6}{colored(self.app_title, 'blue', attrs=['bold'])}{s.DSH * 6}", 1, ) self.dashes = self.justify( s.DSH * (len(self.head) - self.ANSI_LEN - 1), 1) self.footer = self.justify( f"{s.DSH * 6}{colored(self.othr_cmd, 'blue', attrs=['bold'])}{s.DSH * 6}\n", 1, ) self.next_prev = f"{colored(self.justify('p', 1), 'yellow')} : Page précédente\
def __init__(self, substitutes_id, substituted_id, substitute_id): """Init.""" self.substitutes_id = substitutes_id self.substituted_id = substituted_id self.substitute_id = substitute_id self.view: ViewDeleteSubstitutes = ViewDeleteSubstitutes() self.product: Product = Product() self.substituted = self.product.retrieve(self.substituted_id) self.substituted = self.substituted[0] self.substitute = self.product.retrieve(self.substitute_id) self.substitute = self.substitute[0] self.indexes = [ str(index) for index in range(1, len(self.view.menu_choices) + 1) ] self.possible_commands = ["delete-", s.BACK_TO_MENU, s.QUIT_APP]
def add_product_service(data): """ 添加资料 :param data:{ "name": self.name, "describe": self.describe, "detail": self.detail, "type": self.type, "pic": self.pic, "category": category, "price": self.price } :return: """ session = g.session product = Product() for key, value in data.items(): setattr(product, key, value) session.add(product) session.commit() return True
def modify_prod(): """ Endpoint to modify a `Product` with respective, product images, attributes and categories. """ logger.info("Modify existing Product...") params = request.get_json() logger.debug(params) if not params: raise errors.ApiError(70001, "Missing required key params") # Verify needed key-values _needed_params = {'product_uuid'} if not _needed_params.issubset(params.keys()): raise errors.ApiError(70001, "Missing required key params") # Call to save Product _prod = Product(params) _prod.save() return jsonify({ "status": "OK", "message": _prod.message, "product_uuid": _prod.product_uuid })
def test_00_product_validation(self): """ Testing Catalogue DB connection """ global new_prod_test print("Testing Prduct validation") prod = Product(new_prod_test) pprint(prod.__dict__) print('Trying to save...') prod.save() # Set UUID new_prod_test['product_uuid'] = prod.product_uuid try: self.assertTrue(prod.product_uuid) except: self.assertFalse(True) # Delete product print(prod.__dict__) print('Deleting test') _del = Product.delete(prod.product_uuid) self.assertTrue(_del) if _del: print(_del)