def main(query): url = 'https://search.shopping.naver.com/search/all.nhn' params = { 'query': query, } res = requests.get(url, params=params) html = res.text soup = BeautifulSoup(html, 'html.parser') for item_tag in soup.select('#_search_list ._itemSection'): name = trim(item_tag.select('a.tit')[0].text) price = int( trim(item_tag.select('.price .num')[0].text).replace(',', '')) img_url = item_tag.select('img[data-original]')[0]['data-original'] img_name = os.path.basename(img_url.split("?", 1)[0]) res = requests.get(img_url, stream=True) item = Item(name=name, amount=price, is_public=True) item.photo.save(img_name, File(res.raw)) item.save() print( name, price, img_url, )
def post(self, request, *args, **kwargs): if request.user.is_authenticated: current_user = get_object_or_404(Profile, user=request.user) if request.user.profile.role == 'US': if request.FILES.get('photo'): current_user.photo = request.FILES.get('photo') form = UserForm(request.POST) if form.is_valid(): if form.cleaned_data['phone_number'] != '': current_user.phone_number = form.cleaned_data[ 'phone_number'] if form.cleaned_data['email'] != '': current_user.user.email = form.cleaned_data['email'] if form.cleaned_data['first_name'] != '': current_user.user.first_name = form.cleaned_data[ 'first_name'] if form.cleaned_data['last_name'] != '': current_user.user.last_name = form.cleaned_data[ 'last_name'] if form.cleaned_data['address'] != '': current_user.address = form.cleaned_data['address'] current_user.user.save() current_user.save() return HttpResponseRedirect('/shop/cabinet/') elif request.user.profile.role == 'MA': item_form = ItemForm(request.POST) if item_form.is_valid(): item = Item(title=item_form.data.get('title'), Brand=item_form.data.get('Brand'), short_description=item_form.data.get( 'short_description'), long_description=item_form.data.get( 'long_description'), price=item_form.data.get('price'), isNewCollection=bool( item_form.data.get('isNewCollection')), image=request.FILES.get('photo')) item.save() return render(request, 'manager_cabinet.html', context={ "User": request.user, "Items": Item.objects.all(), "form": ItemForm() }) else: return render(request, 'manager_cabinet.html', context={ "User": request.user, "Items": Item.objects.all(), "form": ItemForm() }) else: return redirect('/shop/login/')
def post(self, request, *args, **kwargs): print("helo") item = Item(ItemForm(request.POST)) item.save() return render(request, 'manager_cabinet.html', context={ "User": request.user, "Items": Item.objects.all(), "form": ItemForm() })
def clean_product(self): product = self.cleaned_data.get('product') product = Product.objects.get(id=int(product)) order = self.cleaned_data.get('order') #order = PurchaseOrder.objects.get(id=int(order)) quantity = int(self.cleaned_data.get('quantity')) price = float(self.cleaned_data.get('price')) ppu = price / quantity for n in range(quantity): i = Item(product=product, purchase_order=order, serial=None, purchase_price=ppu, sale_price=None) i.save() return product
def addItem(request): fake = Faker() if request.user.is_authenticated: userM = UserModel.objects.filter(user__exact=request.user) user = request.user context = {"userM": userM, "user": user} if request.method == 'POST': form = AddItemForm(request.POST) if form.is_valid(): fakeStore = Store(name=fake.text(50), location=fake.text(10)) fakeStore.save() i_name = form.cleaned_data['new_item'] i_store = fakeStore i_price = fake.random_int(1, 100) i_aisle = fake.random_int(1, 26) i_short_description = fake.text(150) i_item_number = fake.random_int(1, 126) item = Item( name=i_name, store=i_store, price=i_price, aisle=i_aisle, short_description=i_short_description, item_number=i_item_number, ) item.save() userM[0].favoriteItems.add(item) userM[0].save() return HttpResponseRedirect('success/') else: fakeStore = Store(name=fake.text(50), location=fake.text(10)) fakeStore.save() i_name = fake.text(50) i_store = fakeStore i_price = fake.random_int(1, 100) i_aisle = fake.random_int(1, 26) i_short_description = fake.text(150) i_item_number = fake.random_int(1, 126) def_item = Item( name=i_name, store=i_store, price=i_price, aisle=i_aisle, short_description=i_short_description, item_number=i_item_number, ) form = AddItemForm(initial={ 'new_item': def_item, }) return render(request, "addItem.html", {'form': form}) return render(request, "login_error.html")
def test_can_create_new_review(self): item = Item(name='Test Product', description='Test description', category='BLACKSMITH', height='4', weight='4', width='4', price='50') item.save() review = Review(user=user.username, reviewed_item=item.name, headline="An exciting new product", rating='5', review_text="test test test test test") review.save() self.assertEqual(review.headline, 'An exciting new product')
def main(): params = dict(query='닌텐도스위치', cat_id='', frm='NVSHATC') url = 'https://search.shopping.naver.com/search/all.nhn' res = requests.get(url, params=params) html = res.text soup = BeautifulSoup(html, 'html.parser') for tag in soup.select('.goods_list ._itemSection'): name = trim(tag.select('.tit')[0].text) amount = trim(tag.select('.price .num')[0].text).replace(',', '') img_url = tag.select('.img > img')[0]['data-original'] img_name = os.path.basename(img_url.split('?')[0]) img_res = requests.get(img_url, stream=True) item = Item(name=name, amount=amount) item.photo.save(img_name, File(img_res.raw)) item.save() print('saved #{}'.format(item.pk))
def checkoutCompra(request): if (request.method == 'POST'): data = json.loads(json.dumps(request.data, ensure_ascii=False)) if (data['usuario'] and data['productos']): productos = data['productos'] fecha = time.strftime("%Y-%m-%d") usuario = get_object_or_404(User, id=data['usuario']['usuario']) compra = Compra() compra.fecha = fecha compra.usuario = usuario compra.save() for prod in productos: productoGuardado = get_object_or_404(producto, id=prod['id']) if (productoGuardado): item = Item() item.producto = productoGuardado item.compra = compra item.cantidad = prod['cantidad'] item.save() return Response("Compra guardada satisfactoriamente", status=status.HTTP_201_CREATED) return Response("Error en el envio de compra", status=status.HTTP_400_BAD_REQUEST)
items = [] for i in range(1, 10): i_name = fake.text(50) i_store = stores[fake.random_int(0, len(stores))-1] i_price = fake.random_int(1,100) i_aisle = fake.random_int(1,26) i_short_description = fake.text(150) i_item_number = fake.random_int(1,126) item = Item(name = i_name, store = i_store, price = i_price, aisle = i_aisle, short_description = i_short_description, item_number = i_item_number, ) item.save() userList.item.add(item) items.append(store); print("\nStore:") for i in Store.objects.all(): print(i) print("\nItem:") for i in Item.objects.all(): print(i) username = "******" password = "******" email = "*****@*****.**"
def getPostItem(request): if request.method == 'GET': # If user is searching based on users if request.GET.get('user_id'): requested_user_id = request.GET.get('user_id') Items = Item.objects.filter(user_id=requested_user_id) try: data = [None] * len(Items) for i in range(0, len(Items)): data[i] = { 'item_id': Items[i].item_id, 'item_name': Items[i].name, 'price': str(Items[i].price), 'stock': Items[i].stock, 'image': str(Items[i].image), 'description': Items[i].desc } data = json.dumps(data) return HttpResponse(data, content_type='application/json') except (KeyError): return HttpResponse( '{"status_code": -6, "message": "Key error"}', content_type='application/json') # If a user is searching with item name: elif request.GET.get('item_id'): # Pull item_id from passed in GET params requested_item_id = request.GET.get('item_id') # If param is not int, exit method and return error message try: int(requested_item_id) except: return HttpResponse( '{"status_code": -7, "message": "Wrong data type input"}', content_type='application/json') # Query for any item that has the same item_id as the passed in params Items = Item.objects.filter(item_id=requested_item_id) try: # Create an empty array that has the length of number of queried data data = [None] * len(Items) # Create an array of dict for each queried data for i in range(0, len(Items)): data[i] = { 'item_id': Items[i].item_id, 'item_name': Items[i].name, 'price': str(Items[i].price), 'stock': Items[i].stock, 'image': str(Items[i].image), 'description': Items[i].desc } data = json.dumps(data) return HttpResponse(data, content_type='application/json') except (KeyError): return HttpResponse( '{"status_code": -6, "message": "Key error"}', content_type='application/json') # If there is no GET params given, return all the existing items Items = Item.objects.order_by() data = [None] * len(Items) for i in range(0, len(Items)): data[i] = { 'item_id': Items[i].item_id, 'item_name': Items[i].name, 'price': str(Items[i].price), 'stock': Items[i].stock, 'image': str(Items[i].image), 'description': Items[i].desc } data = json.dumps(data) return HttpResponse(data, content_type='application/json') # POST method (insert or update) elif request.method == 'POST': # Check if user is logged in. If not, exit and return -1 if not request.user.is_authenticated: return HttpResponse( '{"status_code": -1, "message": "Login required"}', content_type='application/json') # Parse in the data sent by user data = json.loads(request.body) # Check if there are any existing item with matching item_id # Update # If there is item_id within passed data, it is an update if 'item_id' in data.keys(): original_entry = Item.objects.get(item_id=data['item_id']) # Check if the owner of this item and the logged-in user is the same user_id item_owner_id = original_entry.user_id if not item_owner_id == request.user.id: return HttpResponse( '{"status_code": -3, "message": "User id does not match the item seller id"}', content_type='application/json') # Iterate through the posted data to see which part of the data the user wishes to change. # Only change the field of a data that has been passed in if 'stock' in data.keys(): original_entry.stock = data['stock'] if 'name' in data.keys(): original_entry.name = data['name'] if 'desc' in data.keys(): original_entry.desc = data['desc'] if 'price' in data.keys(): original_entry.price = data['price'] original_entry.save() # Post new item else: name = data['name'] user_id = request.user.id price = data['price'] # image_id = data['image_id'] stock = data['stock'] new_item = Item(name=name, price=price, stock=stock, user_id=user_id) new_item.save() new_item_id = new_item.item_id data = { "status_code": 0, "message": "Success", "item_id": new_item_id } print('A New item has been added successfully') return HttpResponse(f'{data}', content_type='application/json')
def import_from_csv(filename, store_name): print 'Starting to import from CSV file %s' % filename with open(filename, 'rU') as csvfile: csvreader = csv.reader(csvfile) rownum = 0 # Remember Col index name_index = -1 category_index = -1 description_index = -1 sku_index = -1 price_index = -1 tax_class_index = -1 # ItemMeta list metaList = dict() # Store StoreQS = Store.objects.filter(name=store_name) store = None if not StoreQS.exists(): store = Store.objects.create( name = unicode(store_name), slug = (store_name.lower()).replace(" ", "_"), address = 'TBD' ) else: store = StoreQS[0] for row in csvreader: if rownum == 0: # Store header row and recognize column name accordingly head = row rownum = 1 for index, colname in enumerate(head): if colname == "Name": name_index = index elif colname == "Category": category_index = index elif colname == "Description": description_index = index elif colname == "SKU": sku_index = index elif colname == "Price": price_index = index elif colname == "Tax Class": tax_class_index = index else: # metaList (key=index, value = column_title) metaList[index] = colname else: try: item = Item() itemMeta = [] for value, attribute in enumerate(row): # Add Item attributes according to column index if value == name_index: item.name = unicode(row[name_index].decode('utf-8')).strip() elif value == category_index: category = None names = re.split('->', row[category_index]) allCategories = Category.objects.filter(store=store) # Split up Category content, iterate from top layer for name in names: name = name.strip(); categories = allCategories.filter(name=name) if category is None: # If is top layer, try to find a category without parent categories = categories.filter(parent__isnull=True) else: categories = categories.filter(parent=category) if not categories.exists(): # If no such Category exists, create one slug = name.lower().replace(" ", "_") category = Category.objects.create( name = name, slug = slug, store = store, parent = category, ) else: category = categories[0] # Assign Item's category since we know it exists now item.category = category elif value == description_index: item.description = unicode(row[description_index].decode('utf-8')) elif value == sku_index: item.sku = unicode(row[sku_index]).strip() elif value == price_index: item.price = Decimal(row[price_index]) elif value == tax_class_index: item.tax_class = Decimal(row[tax_class_index]) else: # Any other column index belong to metaData meta = ItemMeta() # Retrieve column name from metaList meta.key = unicode(metaList[value]).strip() meta.value = unicode(attribute.decode('utf-8')).strip() # We can't save itemMeta until the Item is saved if len(meta.value) > 0: itemMeta.append(meta) item.save() except Exception as e: print row[name_index] print e for meta in itemMeta: # Now Item is successfully saved, we can save all lingering meta meta.item = item meta.save()
return parent d = json.load(open("init/amebafurugiya.json")) for row in d[:200]: # print(str(row).encode('utf-8').decode('latin-1')) i = Item( # image='shop_items/' + row['image_paths'][0].lstrip('full/'), category=get_category(row['categories']), price=row.get('price', [''])[0], brand=row.get('brand', [''])[0], exhibiter=row.get('exhibiter', [''])[0], delivery_days=row.get('delivery_days', [''])[0], delivery_service=row.get('delivery_service', [''])[0], delivery_source=row.get('delivery_source', [''])[0], rank=row.get('rank', [''])[0], size=row.get('size', [''])[0], image_url=row['image_urls'][0], page_url=row['url'][0], details=row.get('details', [''])[0], ) filename = row['image_paths'][0][5:] with open('/srv/app/data/images/' + filename, 'rb') as f: content = File(f) i.image.save( filename, content, save=False, ) i.save()