def setUp(self): super().setUp() self.seller = Seller( username='******', password='******', first_name='Michael', last_name='Fassbender', company_name='The Brotherhood', address='900 Exposition Boulevard, Los Angeles', description= 'The Brotherhood was founded by Magneto and its members were his primary allies in his early battles with the X-Men during the 1960s. The original Brotherhood ultimately disbanded, with Quicksilver and Scarlet Witch going on to become members of the Avengers.' ) self.seller.save() self.product = Product( name='Cerebro', category='Cosmetics', price=1749.99, num_stocks=3, short_description='Read minds across the globe!', full_description= 'Cerebro is a fictional device appearing in American comic books published by Marvel Comics. The device is used by the X-Men (in particular, their leader, Professor Charles Xavier) to detect humans, specifically mutants.', image='http://localhost:8000/images/cerebro.jpg', seller=self.seller) self.product.save() self.cart = Cart(buyer=self.buyer) self.cart.save()
def put(self, id): """ Edit product data """ parser.replace_argument('name', required=False) parser.replace_argument('price', required=False) parser.replace_argument('description', required=False) data = parser.parse_args() item = Product.find_by_id(id) if not item: return {"messages": "User not found"}, 404 name = data.get('name', None) if name and Product.find_by_name(name): return {'message': f'Product {name} already exists'}, 400 for key, value in data.items(): if data[key] is not None: setattr(item, key, value) try: item.save() return { 'payload': { 'product': item.to_json(), } } except Exception as e: return {'message': 'Error while updating the product'}, 500
def save_products(data): for i in data: try: if db.session.query( Product.query.filter( Product.name == i['name']).exists()).scalar(): return b_id = Brand.query.with_entities(Brand.id).filter( Brand.name == i['manufacturer']).limit(1).scalar() try: if not b_id: b = Brand() b.name = i['manufacturer'] db.session.add(b) db.session.commit() b_id = b.id except (IntegrityError, OperationalError, InvalidRequestError) as e: db.session.rollback() print(e) product = Product() product.name = i['name'] product.url = i['url'] product.brand_id = b_id product.therapeutic_name = i['genericname'] product.price = i['price']['INR']['default'] product.drug_type = i['drug_type'] product.formulation_types = i['formulation_types'] product.dosage = i['dosage'] if 'dosage' in i else "" db.session.add(product) db.session.commit() if 'categories_without_path' and i['categories_without_path']: for x in i['categories_without_path']: c_id = Category.query.with_entities(Category.id).filter( Category.name == x).limit(1).scalar() try: if not c_id: c = Category() c.name = x db.session.add(c) db.session.commit() c_id = c.id if c_id: pc = ProductCategory() pc.product_id = product.id pc.category_id = c_id db.session.add(pc) db.session.commit() except (IntegrityError, OperationalError, InvalidRequestError) as e: db.session.rollback() print(e) except (IntegrityError, OperationalError, InvalidRequestError) as e: db.session.rollback() print(e) pass
def models_create(): form = ModelForm(request.form) if not form.validate(): return render_template("models/list.html", form=form, models=Product.query.all(), manufExists=Manufacturer.query.count() > 0, listeroo=Product.listByBrokenPercent()) t = Product(form.name.data) t.manufacturer = form.manufacturer.data t.eol = False db.session().add(t) db.session().commit() return redirect(url_for("models_index"))
def setUp(self): super().setUp() self.product_4 = Product( name='Web Shooters', category='Kids', price=299.99, num_stocks=220, short_description= 'Shoot webs everywhere to satisfy your childish dreams!', full_description= 'Web Shooters are twin devices, worn on your wrists beneath the gauntlets of your costume, that can shoot thin strands of a special \'web fluid\' (the chemical composition of which is not known) at high pressure.', image='web_shooters.jpg', seller=self.seller) self.product_4.save()
def get_product(self, product_id: str) -> Product: try: return next( Product.parse_obj(product) for product in self.data if product["id"] == product_id) except StopIteration: raise NotFound(f"Product {product_id} not found")
def get(self, id): """ Return product """ item = Product.find_by_id(id) if item: return {'payload': {'product': item.to_json()}} return {"messages": "Product not found"}, 404
class RegisteredBuyersWithCartsTestCase(RegisteredBuyersTestCase): @classmethod def setUp(self): super().setUp() self.seller = Seller( username='******', password='******', first_name='Michael', last_name='Fassbender', company_name='The Brotherhood', address='900 Exposition Boulevard, Los Angeles', description= 'The Brotherhood was founded by Magneto and its members were his primary allies in his early battles with the X-Men during the 1960s. The original Brotherhood ultimately disbanded, with Quicksilver and Scarlet Witch going on to become members of the Avengers.' ) self.seller.save() self.product = Product( name='Cerebro', category='Cosmetics', price=1749.99, num_stocks=3, short_description='Read minds across the globe!', full_description= 'Cerebro is a fictional device appearing in American comic books published by Marvel Comics. The device is used by the X-Men (in particular, their leader, Professor Charles Xavier) to detect humans, specifically mutants.', image='http://localhost:8000/images/cerebro.jpg', seller=self.seller) self.product.save() self.cart = Cart(buyer=self.buyer) self.cart.save() def add_item_to_cart(self, product_id): return self.client.post('/buyers/1/cart/items/', json.dumps({'product_id': product_id}), content_type='application/json') def update_item_quantity(self, action): return self.client.post('/buyers/1/cart/items/1/', json.dumps({'action': action}), content_type='application/json')
def delete(self, id): """ Delete user """ item = Product.find_by_id(id) if not item: return {"messages": "Product not found"}, 404 try: item.delete() return {"payload": {}, "messages": "Product deleted"} except: return {'message': 'Error while deleting the product'}, 500
def retrieve_and_create_product(request, seller_id): if (request.method == 'GET'): products_list = Product.objects.filter( Q(seller_id=seller_id) | Q(seller_id=None)).order_by('id') products = [] for product in products_list: products.append({ 'product_id': product.id, 'seller_id': product.seller_id, 'name': product.name, 'category': product.category, 'price': product.price, 'short_description': product.short_description, 'image': product.image }) return JsonResponse({'products': products}) elif (request.method == 'POST'): seller = get_object_or_404(Seller, id=seller_id) request_body = json.loads(request.body.decode('utf-8')) product = Product(name=request_body['name'], category=request_body['category'], price=request_body['price'], num_stocks=request_body['num_stocks'], short_description=request_body['short_description'], full_description=request_body['full_description'], image='http://localhost:8000{}{}'.format( settings.MEDIA_URL, request_body['image']), seller=seller) product.save() return JsonResponse({'product_id': product.id}, status=201) else: return HttpResponse(status=405)
class AdminWithProductsTestCase(AdminTestCase): @classmethod def setUp(self): super().setUp() self.seller = Seller( username='******', password='******', first_name='Michael', last_name='Fassbender', company_name='The Brotherhood', address='900 Exposition Boulevard, Los Angeles', description='The Brotherhood was founded by Magneto and its members were his primary allies in his early battles with the X-Men during the 1960s. The original Brotherhood ultimately disbanded, with Quicksilver and Scarlet Witch going on to become members of the Avengers.' ) self.seller.save() self.product_1 = Product( name='Cerebro', category='Cosmetics', price=1749.99, num_stocks=3, short_description='Read minds across the globe!', full_description='Cerebro is a fictional device appearing in American comic books published by Marvel Comics. The device is used by the X-Men (in particular, their leader, Professor Charles Xavier) to detect humans, specifically mutants.', image='http://localhost:8000/images/cerebro.jpg', seller=self.seller ) self.product_1.save() self.product_2 = Product( name='Invisibility Cloak', category='Clothes', price=799.99, num_stocks=3, short_description='Hide from anything, even death!', full_description='An invisibility cloak is a magical garment which renders whomever or whatever it covers unseeable. These are common items that are massed produced in the wizarding world. The first known cloak was made by Death for Ignotus Peverell in the 13th century and it is one of a kind.', image='http://localhost:8000/images/invisibility_cloak.jpg', seller=self.seller ) self.product_2.save() self.product_3 = Product( name='Mjolnir', category='Sports', price=2499.99, num_stocks=3, short_description='Weight-lifting like never before!', full_description='In Norse mythology, Mjolnir is the hammer of Thor, a major Norse god associated with thunder. Mjolnir is depicted in Norse mythology as one of the most fearsome and powerful weapons in existence, capable of leveling mountains.', is_confirmed=True, image='http://localhost:8000/images/mjolnir.jpg', seller=self.seller ) self.product_3.save()
def put(self, id): """ Edit sale data """ parser.replace_argument('user_id', help='user_id cannot be blank', required=False) parser.replace_argument('product_id', help='product_id cannot be blank', required=False) data = parser.parse_args() user_id = data.get('user_id') if user_id: if not User.find_by_id(user_id): return {'message': f'User {user_id} doesn\'t exist'}, 400 product_id = data.get('product_id') if product_id: if not Product.find_by_id(product_id): return {'message': f'Product {product_id} doesn\'t exist'}, 400 item = Sale.find_by_id(id) if not item: return {"messages": "Sale not found"}, 404 for key, value in data.items(): if data[key] is not None: setattr(item, key, value) try: item.save() return { 'payload': { 'sale': item.to_json(), } } except Exception as e: return {'message': 'Error while updating the sale'}, 500
def post(self): parser.replace_argument('user_id', help='user_id cannot be blank', required=True) parser.replace_argument('product_id', help='product_id cannot be blank', required=True) data = parser.parse_args() user_id = data.get('user_id') if not User.find_by_id(user_id): return {'message': f'User {user_id} doesn\'t exist'}, 404 product_id = data.get('product_id') if not Product.find_by_id(product_id): return {'message': f'Product {product_id} doesn\'t exist'}, 404 # create new user item = Sale(user_id=data.get('user_id'), product_id=data.get('product_id')) if data.get('date'): item.date = datetime.strptime(data.get('date'), '%Y-%m-%d') if data.get('commission_paid'): item.commission_paid = data.get('commission_paid') try: # Saving user in DB and Generating Access and Refresh token item.save() return { 'payload': { 'sale': item.to_json(), } }, 201 except Exception as e: return {'message': 'Error while saving the sale'}, 500
class RegisteredSellersWithProductsTestCase(RegisteredSellersTestCase): @classmethod def setUp(self): super().setUp() self.product_1 = Product( name='Cerebro', category='Cosmetics', price=1749.99, num_stocks=3, short_description='Read minds across the globe!', full_description= 'Cerebro is a fictional device appearing in American comic books published by Marvel Comics. The device is used by the X-Men (in particular, their leader, Professor Charles Xavier) to detect humans, specifically mutants.', is_confirmed=True, image='http://localhost:8000/images/cerebro.jpg', seller=self.seller) self.product_1.save() self.product_2 = Product( name='Invisibility Cloak', category='Clothes', price=799.99, num_stocks=3, short_description='Hide from anything, even death!', full_description= 'An invisibility cloak is a magical garment which renders whomever or whatever it covers unseeable. These are common items that are massed produced in the wizarding world. The first known cloak was made by Death for Ignotus Peverell in the 13th century and it is one of a kind.', is_confirmed=True, image='http://localhost:8000/images/invisibility_cloak.jpg', seller=self.seller) self.product_2.save() self.product_3 = Product( name='Mjolnir', category='Sports', price=2499.99, num_stocks=3, short_description='Weight-lifting like never before!', full_description= 'In Norse mythology, Mjolnir is the hammer of Thor, a major Norse god associated with thunder. Mjolnir is depicted in Norse mythology as one of the most fearsome and powerful weapons in existence, capable of leveling mountains.', image='http://localhost:8000/images/mjolnir.jpg', seller=self.seller) self.product_3.save()
def save_med_products(data): for i in data: if 'productName' not in i: continue try: if db.session.query( Product.query.filter( func.lower(Product.name) == func.lower( i['productName'])).exists()).scalar(): continue b_id = Brand.query.with_entities(Brand.id).filter( func.lower(Brand.name) == func.lower(i['manufacturer'])).limit( 1).scalar() try: print(i['productName']) if not b_id: b = Brand() b.name = i['manufacturer'] db.session.add(b) db.session.commit() b_id = b.id except (IntegrityError, OperationalError, InvalidRequestError) as e: db.session.rollback() print(e) product = Product() product.name = i['productName'] product.brand_id = b_id # product.therapeutic_name = i['genericname'] product.price = i['packSizeMrp'] # product.drug_type = i['drug_type'] product.formulation_types = i['productFormName'] # product.dosage = i['dosage'] if 'dosage' in i else "" db.session.add(product) db.session.commit() except (IntegrityError, OperationalError, InvalidRequestError) as e: db.session.rollback() print(e) pass
def post(self): data = parser.parse_args() name = data['name'] # Checking that user is already exist or not if Product.find_by_name(name): return {'message': f'Product {name} already exists'}, 400 # create new user item = Product( name=name, price=data['price'], description=data.get('description', ''), ) try: # Saving user in DB and Generating Access and Refresh token item.save() return { 'payload': { 'product': item.to_json(), } }, 201 except: return {'message': 'Error while saving the product'}, 500
def get(self): """ Return all products """ return Product.return_all()
def get_products(self) -> List[Product]: return [Product.parse_obj(product) for product in self.data]
def models_index(): return render_template("models/list.html", models=Product.query.all(), form=ModelForm(), manufExists=Manufacturer.query.count() > 0, listeroo=Product.listByBrokenPercent() )