def webpage(request, *args): result = [] if request.method == "POST": result = [] data = request.POST.get('data', '') for objects in Product.objects.all(): if data.lower() in Product.get_text(objects).lower(): help = Product.get_helpfulness(objects) good_rating = int(help.split("/")[0]) bad_rating = int(help.split("/")[1]) - good_rating result.append([ Product.get_score(objects), good_rating, bad_rating, Product.get_text(objects) ]) if not result == []: result.sort(key=lambda x: (-x[0], -x[1], x[2])) output = result[0][3] else: output = "" message = { 'review_text': output, } return render(request, "webpage.html", message) return render(request, "webpage.html")
def register(request): sku = request.GET.get('sku', 'None') name = request.GET.get('name', 'None') qty = request.GET.get('qty', 'None') price = request.GET.get('price', 'None') p = Product(sku = sku, name = name, qty = qty, price = price) p.save() processed_p = {'sku': sku, 'name': name, 'qty': qty, 'price': price} return HttpResponse(json.dumps(processed_p), content_type = 'application/json')
def addproduct(request): if request.method == "POST": #Get the posted form MyLoginForm = AddProductForm(request.POST) if MyLoginForm.is_valid(): name = MyLoginForm.cleaned_data['name'] pro = Product(name=name, image="002376970", description="ASDASDASD") pro.save() res = "Added" return HttpResponse(res)
def load_products(): '''Import products from API and add them in the database''' nbr = 0 for category in CATS: cat = Category(name=category) cat.save() payload = { 'action': 'process', 'tagtype_0': 'categories', 'tag_contains_0': 'contains', 'tag_0': category, 'countries': 'France', 'page_size': '250', 'json': 1 } reponse = requests.get('https://fr.openfoodfacts.org/cgi/search.pl', \ params=payload) data = reponse.json() try: for product in data['products']: try: name = product['product_name_fr'] except KeyError: try: name = product['product_name'] except KeyError: pass try: nutrition_grade = product['nutrition_grade_fr'] except KeyError: try: nutrition_grade = product['nutrition_grade'] except KeyError: pass url = product['url'] image = product['image_front_url'] try: nutrition_image = product["image_nutrition_small_url"] except KeyError: pass name = name.replace("\n", " ") name = name.replace("'", "'") product = Product(name=name, category=cat, \ nutrition_grade=nutrition_grade, url=url,\ img_url=image, nut_url=nutrition_image) nbr += 1 product.save() except KeyError: pass
def saveData(request): if request.method == 'POST': if request.POST['name'] == '' or request.POST[ 'price'] == '' or request.POST['quantity'] == '': messages.error(request, 'all fields required') return redirect('insert') else: new_product = Product(name=request.POST['name'].strip(), price=request.POST['price'].strip(), quantity=request.POST['quantity'].strip()) new_product.save() messages.success(request, "Saved") return redirect('insert')
def test_product_model(self): product = Product(name="Nokia", price=45.0, category=Category(name="smartphone")) db.session.add(product) db.session.commit() self.assertEqual(Product.query.count(), 1)
def add_product(): """ Add a new product to the database """ categories = ProductCategory.query.order_by('name') form = ProductForm() form.category.choices = [(c.id, c.name) for c in categories] # if request.method == 'POST': # category = ProductCategory.query.filter_by( # id=form.category.data).first() # return 'Name: {}, Category: {}'.format(form.name.data, category.name) if form.validate_on_submit(): category = ProductCategory.query.filter_by( id=form.category.data).first() product = Product( name=form.name.data, description=form.description.data, # image=form.image.data, # Create a method to make a thumbnail from a full image? # thumbnail= # Not sure about how to add category to a new product category=category, weight=form.weight.data) db.session.add(product) db.session.commit() flash('Your product has been added!') return redirect(url_for('store.store')) return render_template('store/crud_product.html', form=form, title='Add Product')
def crawling(request): crawl_url = request.POST.get('crawl_url') crawl_brand = request.POST.get('crawl_brand') crawl_number = request.POST.get('crawl_number') crawl_selectname = request.POST.get('crawl_selectname') crawl_selectprice = request.POST.get('crawl_price') crawl_selectimage = request.POST.get('crawl_image') categori = request.POST.get('categori') response = urlopen(crawl_url) soup = BeautifulSoup(response, 'html.parser') i = 1 name = "" price = "" image = "" brandnum = crawl_brand + str(crawl_number) cr_name = soup.select(crawl_selectname) for a in cr_name: name = a.get_text() print(name) cr_price = soup.select(crawl_selectprice) for b in cr_price: price = b.get_text() print(price) #thumbimg=soup.select(pdid+str(num)+"> div:nth-child(1) > a > img") cr_img = soup.select(crawl_selectimage) for c in cr_img: image = c.find("img")["src"] print(image) if name == None: msg = "nameselect 공백이다" return render(request, 'crawling.html', {'msg': msg}) elif price == None: msg = "가격 공백이다" return render(request, 'crawling.html', {'msg': msg}) elif image == None: msg = "이미지 공백이다" return render(request, 'crawling.html', {'msg': msg}) else: doc_ref = db.collection("product") doc_ref_random = db.collection("product").document(brandnum) doc_ref_random.set( Product(name, price, brandnum, image, categori, crawl_brand).to_dict()) msg = "업로드 성공적" return render(request, 'crawling.html', {'msg': msg})
def handle(self, *args, **kwargs): base_dir = Path(__file__).resolve().parent.parent file_path = os.path.join(base_dir, 'Files\\foods.txt') data_file = open(file_path, 'r') lines = data_file.readlines() product_list = { 'productId': None, "userId": None, 'helpfulness': None, 'profileName': None, 'score': None, 'time': None, 'summary': None, 'text': None } for line in lines: if line != "\n" and line != "" and line is not None: res = re.split(':', line) index = re.split('/', res[0]) product_list[index[1].strip()] = res[1].strip() elif product_list['productId'] is not None: product = Product(productid=product_list['productId'], userid=product_list['userId'], helpfulness=product_list['helpfulness'], profilename=product_list['profileName'], score=product_list['score'], time=product_list['time'], summary=product_list['summary'], text=product_list['text']) product.save() print(product_list['productId'] + " has been loaded successfully") product_list['productId'] = None if product_list['productId'] is not None: product = Product(productid=product_list['productId'], userid=product_list['userId'], helpfulness=product_list['helpfulness'], profilename=product_list['profileName'], score=product_list['score'], time=product_list['time'], summary=product_list['summary'], text=product_list['text']) product.save() print(product_list['productId'] + " has been loaded successfully") product_list['productId'] = None print("All Model has been Loaded Successfully")
def create_product(request): if request.method == 'POST': product = Product() product.shop = request.user product.name = request.POST.get("name") product.description = request.POST.get("description") product.price = request.POST.get("price") product.save() new_stripe_product = stripe.Product.create( name=product.name, id=product.id, description=product.description) new_stripe_product.metadata["shop"] = product.shop new_stripe_product.metadata["price"] = product.price new_stripe_product.save() return redirect("home") else: return render(request, 'myapp/home.html')
def getdata(request, option, price, username, phonenum, address, uid, delivery_message, product_id): delivery_lis = [] prd_ref = db.collection(u'product').document(product_id) prd_docs = prd_ref.get() dictionary = literal_eval(option) if prd_docs.exists: products = Product.from_dict(prd_docs.to_dict()) img = products.downloadurl brandname = products.brand product_name = products.name doc_ref = db.collection("delivery") doc_ref_random = db.collection("delivery").document() doc_ref_random.set( Delivery(brandname, product_name, dictionary, price, username, phonenum, address, firestore.SERVER_TIMESTAMP, "배송전", "", "", uid, delivery_message, img, product_id).to_dict()) user_doc = db.collection("users").document(uid).collection( "delivery").document(doc_ref_random.id) user_doc.set( Delivery(brandname, product_name, dictionary, price, username, phonenum, address, firestore.SERVER_TIMESTAMP, "배송전", "", "", uid, delivery_message, img, product_id).to_dict()) delievery_par = Delivery.from_dict( Delivery(brandname, product_name, dictionary, price, username, phonenum, address, firestore.SERVER_TIMESTAMP, "배송전", "", "", uid, delivery_message, img, product_id).to_dict()) # delivery=Delivery.from_dict(delivery_docs.to_dict()) delivery_lis.append(delievery_par) #print(delivery_lis) #유저에서 딜리버리 가져오기 else: print(u'No such document!') return render(request, 'getdata.html', {'delivery_lis': delivery_lis})
def place_order(request): if request.user.is_authenticated: testuser = request.user else: testuser = "" msg = '' prodlist = Product.objects.all() if request.method == 'POST': form = forms.OrderForm(request.POST) if form.is_valid(): order = form.save(commit=False) if order.num_unit <= order.product.stock: product = Product.objects.get(name=order.product.name) product.stock = product.stock - order.num_unit product.save() msg = 'Your order has been placed successfully.' p = Product() p.refill(order.product.name) order.save() else: msg = 'We do not have sufficient stock to fill your order.' p = Product() p.refill(order.product.name) order.save() return render(request, 'myapp/order_response.html', { 'msg': msg, 'testuser': testuser }) # else: # msg = "Invalid user, select logged in user to place order" # return render(request, 'myapp/order_response.html', {'msg': msg, 'testuser': testuser}) else: form = OrderForm() return render(request, 'myapp/placeorder.html', { 'form': form, 'msg': msg, 'prodlist': prodlist, 'testuser': testuser })
def add_product(request): '''Create a new Product. :param name(required): the name of the product. :type name: string :param color(required): the color of the product :type color: string :param image(required): the image need to be used in the product. :type image: file :param price(required): the price of the product :type price: float :param category(required): the id of the category that need to be used :type category: integer :returns: message :rtype: dictionary ''' try: if request.POST and request.FILES: is_error = False name = request.data.get('name') color = request.data.get('color') image = request.data.get('image') category_id = request.data.get('category') price = request.data.get('price') if not name: message = 'Name is Mandatory' is_error = True if not color: message = 'Color is Mandatory' is_error = True if not category_id: message = 'Category Id is Mandatory' is_error = True if not price: message = 'Price is Mandatory' is_error = True if is_error: return Response({"error": message}, status=status.HTTP_400_BAD_REQUEST) category = Category.objects.get(id=category_id) p = Product(name=name, color=color, image=image, category=category, price=price) p.save() return Response({"message": 'Product Added Successfully'}) elif not request.FILES: return Response({"error": "Image is Mandatory."}, status=status.HTTP_400_BAD_REQUEST) else: return Response({"error": "All Fields are Mandatory."}, status=status.HTTP_400_BAD_REQUEST) except ValueError as e: return Response({"error": str(e)}, status=status.HTTP_400_BAD_REQUEST) except KeyError as e: return Response({"error": str(e)}, status=status.HTTP_400_BAD_REQUEST) except Exception as e: return Response({"error": str(e)}, status=status.HTTP_400_BAD_REQUEST)
def sample_filling(request): p = Product(sku = 'A0B1C2D3', name = 'Bread', qty = 8, price = 3.4) p.save() p = Product(sku = 'B0C1D2E3', name = 'Eggs', qty = 4, price = 2.1) p.save() p = Product(sku = 'C0D1E2F3', name = 'Milk', qty = 6, price = 5.2) p.save() p = Product(sku = 'D0E1F2G3', name = 'Cheese', qty = 0, price = 9.9) p.save() p = Product(sku = 'E0F1G2H3', name = 'Rice', qty = 2, price = 7.5) p.save() p = Product(sku = 'F0G1H2I3', name = 'Pasta', qty = 7, price = 8.0) p.save() p = Product(sku = 'G0H1I2J3', name = 'Sugar', qty = 0, price = 0.1) p.save() p = Product(sku = 'H0I1J2K3', name = 'Salt', qty = 5, price = 1.7) p.save() return HttpResponse(process_products(Product.objects.all()), content_type = 'application/json')
def create_admin(request): # Title=request.POST.get('Title') # Detail=request.POST.get('Detail') # url=request.POST.get('url') # categori=request.POST.get('categori') # if not Title : # messg="Title 입력하세요" # return render(request ,'create.html',{"messg":messg}) # if not Detail : # messg="Detail 입력하세요" # return render(request ,'create.html',{"messg":messg}) # if not url : # messg="url을 업로드 하세요" # return render(request ,'create.html',{"messg":messg}) # if not categori : # messg="categori 업로드 하세요" # return render(request ,'create.html',{"messg":messg}) adminBrandNumber = request.POST.get('adminBrandNumber') print("브랜드넘버:" + adminBrandNumber) adminBrandName = request.POST.get('adminBrandName') print("브랜드이름:" + adminBrandName) adminProductCategory = request.POST.get('adminProductCategory') print("카테고리:" + adminProductCategory) adminProductName = request.POST.get('adminProductName') print("상품이름:" + adminProductName) adminProductPrice = request.POST.get('adminProductPrice') print("가격:" + adminProductPrice) adminProuctMaimImage = request.POST.get('adminProuctMaimImage') print("메인이미지:" + adminProuctMaimImage) cnt = request.POST.get('cnt') print("카운트:" + cnt) lis_detail_img = [] if cnt != "": cnt = int(cnt) for count in range(1, cnt + 1): adminProuctDetailImageCnt = "adminProuctDetailImage" + str(count) print("count:" + adminProuctDetailImageCnt) img = request.POST.get(adminProuctDetailImageCnt) print("가져온 이미지:" + img) lis_detail_img.append(img) adminDetailText = request.POST.get('adminDetailText') print("상세텍스트:" + adminDetailText) documentId = adminBrandName + adminBrandNumber #file=request.POST.get('file') doc_ref = db.collection("product") doc_ref_random = db.collection("product").document(documentId) doc_ref_random.set( Product(adminProductName, adminProductPrice, documentId, adminProuctMaimImage, adminProductCategory, adminBrandName, lis_detail_img, adminDetailText, firestore.SERVER_TIMESTAMP, format(int(adminProductPrice), ',')).to_dict()) print(firestore.SERVER_TIMESTAMP) number = 12345 number = format(number, ',') print(number) return render(request, "createadmin.html")
def test_add_product_to_category(self): c = ProductCategory(name='fruits') p = Product(name='apple', category=c) db.session.add(c, p) db.session.commit() self.assertEqual(p.category.name, 'fruits')