def addProduct(request): Username = request.GET.get('username') Name = request.GET.get('name') Description = request.GET.get('description') Stock = request.GET.get('stock') Active = request.GET.get('active') Display = request.GET.get('dp') cost = request.GET.get('costprice') sell = request.GET.get('sellprice') Discount= request.GET.get('discount') if Active == 'y': Active = True else: Active = False user1 = User.objects.get(username=Username) # userD = userdetails.object.get(user = user1) proid = "PROD"+str(random.randint(9999,99999)) add = Product(user=user1,productName=Name,productid=proid,productDescription=Description,stock=Stock,active=Active,display=Display,costPrice=cost,sellingPrice=sell,discount=Discount) add.save() return JsonResponse({'result':1,'message':'Success'})
def handle(self, *args, **options): module_dir = os.getcwd() # get current directory file_path = os.path.join(module_dir, options['file']) with open(file_path) as f: content = f.readlines() # you may also want to remove whitespace characters like `\n` at the end of each line lines = [x.strip() for x in content] lines.pop(0) for curr_line in lines: fields = curr_line.split('\t') try: product = Product.objects.get(product_id=fields[0]) except: product = None if not product: print('adding product') product = Product(product_id=fields[0], description=fields[1]) product.save() location = Location(product=product, datetime=fields[2], \ longitude=fields[3], latitude=fields[4], elevation=fields[5]) location.save()
def products(request): if request.method == 'POST': products = request.data.get('product', None) for product in products: name = product.get('name', None) company_name = product.get('company_name', None) ingredient_list = product.get('ingredient_list', None) product_to_ingredient = product.get('product_to_ingredient', None) product_to_function = product.get('product_to_function', None) heavy_metal = product.get('heavy_metal', None) sungsang = product.get('sungsang', None) intake_hint = product.get('intake_hint', None) intake_method = product.get('intake_method', None) preservation = product.get('preservation', None) image_url = product.get('image_url', None) product = Product(name=name, company_name=company_name, ingredient_list=ingredient_list, heavy_metal_list=heavy_metal, sungsang=sungsang, intake_hint=intake_hint, intake_method=intake_method, preservation=preservation, image_url=image_url) product.save() for my_ingredient in product_to_ingredient: ingredient = Ingredient.objects.get(name=my_ingredient) product.product_to_ingredient.add(ingredient) for my_function in product_to_function: function = Function.objects.get(name=my_function) product.product_to_function.add(function) break return Response(status=status.HTTP_201_CREATED)
def post(self, request): product_data = request.POST total_errors = 0 product_report = [] for product in product_data: new_product = Product( id=product.get('id'), name=product.get('name'), value=product.get('value'), discount_value=product.get('discount_value'), stock=product.get('stock'), ) errors = get_product_error(new_product) if errors: total_errors += 1 product_report.append({'product_id': id, 'errors': errors}) else: new_product.save() response = {'status': 'OK'} if total_errors: response = { 'status': 'ERROR', 'products_report': product_report, 'number_of_products_unable_to_parse': total_errors, } return JsonResponse(response)
def setUp(self): '''Definir un producto''' self.name = "Prueba de creación de productos" self.tags = ProductTags(name='nuevo') self.brand = Brand(name='Nike') self.brand.save() self.producto = Product(name='Producto 1', description='Producto de prueba 1', brand=self.brand)
def addNewProduct(): current_id = get_jwt_identity() img = request.json.get("image", None) sellerid = request.json.get("sellerid", None) productName = request.json.get("productname", None) description = request.json.get("description", None) category = request.json.get("category", None) price = request.json.get("price", None) item_status = request.json.get("itemstatus", None) if not img: return jsonify({"msg": "No image was uploaded!."}), 400 if not description: return jsonify({"msg": "Please enter a valid description"}), 400 if not category: return jsonify({"msg": "Please enter a valid category"}), 400 if not price: return jsonify({"msg": "Please enter a valid price"}), 400 if not item_status: return jsonify({"msg": "Please enter a valid item status"}), 400 else: new_product = Product() new_product.productName = productName new_product.fk_id = sellerid new_product.description = description new_product.category = category new_product.price = price new_product.item_status = item_status new_product.img = img db.session.add(new_product) db.session.commit() return jsonify( {"msg": "The product has being successfully registered."}), 200
def main(): # read the json data with open('data.json') as json_data: data = json.load(json_data) cats = {} i = 1 # find the categories, and replace them with the # new category id (created below) for prod in data['data'].values(): if prod['category'] not in cats: cats[prod['category']] = i i += 1 prod['category'] = cats[prod['category']] # create the categories for cat_name, cat_id in cats.items(): new_cat = Category() new_cat.id = cat_id new_cat.title = cat_name new_cat.save() # create the products for prod in data['data'].values(): p = Product() p.name = prod['name'] p.description = prod['description'] p.price = prod['price'] p.filename = prod['filename'] p.category = Category.objects.get(id=prod['category']) p.save()
def setUp(self): self.order_data = { 'order_type': 'Privé', 'items': [], 'title': 'Test 1734', 'description': 'Nice order', 'geom': { 'type': 'Polygon', 'coordinates': [[[2528577.8382161376, 1193422.4003930448], [2542482.6542869355, 1193422.4329014618], [2542482.568523701, 1199018.36469272], [2528577.807487005, 1199018.324372703], [2528577.8382161376, 1193422.4003930448]]] }, } management.call_command('fixturize') self.userPrivate = UserModel.objects.create_user( username="******", password="******", ) self.orderTypePrivate = OrderType.objects.create(name="Privé", ) self.formats = DataFormat.objects.bulk_create([ DataFormat(name="Geobat NE complet (DXF)"), DataFormat(name="Rhino 3DM"), ]) self.pricing_free = Pricing.objects.create(name="Gratuit", pricing_type="FREE") self.pricing_manual = Pricing.objects.create(name="Manuel", pricing_type="MANUAL") self.products = Product.objects.bulk_create([ Product(label="MO - Cadastre complet (Format A4-A3-A2-A1-A0)", pricing=self.pricing_free, free_when_subscribed=True), Product(label="Maquette 3D", pricing=self.pricing_manual), ]) self.contact = Contact.objects.create( first_name='Jean', last_name='Doe', email='*****@*****.**', postcode=2000, city='Lausanne', country='Suisse', company_name='Marine de Colombier', phone='+41 00 787 29 16', belongs_to=self.userPrivate) url = reverse('token_obtain_pair') resp = self.client.post(url, { 'username': '******', 'password': '******' }, format='json') self.assertEqual(resp.status_code, status.HTTP_200_OK) self.assertTrue('access' in resp.data) self.token = resp.data['access']
def test_puede_borrar_producto(self): self.tags = ProductTags(name='nuevo') self.brand = Brand(name='Nike') self.brand.save() self.producto = Product(name='Producto 1', description='Producto de prueba 1', brand=self.brand) self.producto.save() self.tags.save() self.producto.tags.add(self.tags) self.producto.save() response = self.client.delete( reverse('api:delete', kwargs={'pk': self.producto.pk})) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Se ha eliminado satisfactoriamente')
def handle(self, *args, **kwargs): path = kwargs['path'] df = pd.read_csv(path) upper_range = len(df) print("Wait Data is being Loaded") try: p = [ Product( name=df['Product'][row], type=df['Product Category'][row], code=int(df['Product Code'][row]), ) for row in range(0, upper_range) ] p_data = Product.objects.bulk_create(p) if p_data: self.stdout.write('Successfully loaded Partner data ..') # for row in range(0, upper_range): # print(df['New Local Unit'][row]) # print(df['District Code'][row]) # print(District.objects.get(n_code=df['District Code'][row])) except Exception as e: print(e)
def newProduct(): try: values = request.json category = values["Category"] if(category): findCategory = Category.query.filter_by(Name= category).first() else: findCategory = Category.query.filter_by(Name= "Todas").first() newproduct = Product(CategoryID= findCategory.CategoryID, Name= values["Name"], Price= values["Price"] , Description= values["Description"], ImageURL= values["ImageURL"] , Available= values["Available"]) db.session.add(newproduct) db.session.commit() response_body = { "status": "OK" } status_code = 200 return jsonify(response_body),200 except: response_body = { "status": "ERROR" } status_code = 200 return jsonify(response_body),200
def add_product(request): if request.method == 'GET': data = { 'title': '添加产品' } return render(request, 'add_product.html', context=data) elif request.method == 'POST': product_name = request.POST.get('product_name') product_desc = request.POST.get('product_desc') product_er = request.POST.get('product_er') products = Product.objects.filter(p_product_name=product_name) if product_name == "" or products.exists(): return redirect(reverse('at:add_product')) else: product = Product() product.p_product_name = product_name product.p_product_desc = product_desc product.p_product_er = product_er product.save() return redirect(reverse('at:product_manage')) return redirect(reverse('at:add_product'))
def setUpClass(cls): super(WhenAddingNewProductTests, cls).setUpTestData() cls.product = Product(name="Apple iPhoneX", price=999.99, manufacturer="Apple", product_type="Smartphone") cls.before_save_product_count = Product.objects.count() cls.product.save()
def route_product_create(name, description, price, company_id): company = Company.query.filter(Company.id == company_id).first() product = Product(name=name, description=description, price=price, company=company) db.session.add(product) db.session.commit() db.session.refresh(product) return product
def setUpClass(cls): super(WhenAddingNewProductWithReleaseDateTests, cls).setUpTestData() cls.passedInDateTime = datetime(2017, 6, 1, tzinfo=timezone.utc) cls.product = Product(name="Apple iPhoneX", price=999.99, manufacturer="Apple", product_type="Smartphone", release_date=cls.passedInDateTime) cls.product.save()
def post(self, request): data_body = json.loads(request.body) category_id = data_body['category']['id'] category = Category.objects.get(id=category_id) product = Product( category = category, name = data_body['name'], price = data_body['price'], rating = data_body['rating'], description = data_body['description'], image = data_body['image'], link = data_body['link'], wlink = data_body['wlink'], like = data_body['like'], ) product.save() return Response({'message': "all good. new product created!`"}, status=status.HTTP_200_OK)
def main(): with open('products.json') as json_file: data = json.load(json_file) products = data['products'] for p in products: print(p['name']) # category cat, created = Category.objects.get_or_create(title=p['category']) # product if Product.objects.filter(name=['name']).count() == 0: product = Product() product.category = cat product.name = p['name'] product.filename = p['filename'] product.id = int(p['id']) product.description = p['description'] product.price = p['price'] product.save()
def test_create_products(self): request = self.request_factory.post('api/v1/products') product = Product( id='456', name='new_product', value=4.8, discount_value=3.8, stock=5, ) response = ProductView.as_view()(request) self.assertEqual(response.status_code, 200)
def post(self, request, *args, **kwargs): ''' Implementación del método POST''' post_data = dict(request.POST) if post_data: lista_tags = [] if post_data.get('tags')[0]: for tag in post_data.get('tags')[0].split(','): nueva_tag = ProductTags(name=tag) nueva_tag.save() lista_tags.append(nueva_tag) post_data.pop('tags', None) marca = Brand.objects.get(pk=post_data.get('brand')[0]) post_data['brand'] = marca producto = Product(**post_data) try: producto.save() for tag in lista_tags: producto.tags.add(tag) producto.save() return JsonResponse( { 'response': 'Producto creado satisfactoriamente', 'id': producto.pk }, safe=False) except Exception as e: return JsonResponse({'response': 'Error al crear el producto'}, safe=False) else: return JsonResponse({'response': 'Petición incorrecta'}, safe=False)
def create_product(request): if request.headers.get('Content-Type') != 'application/json': data = {'error': 'Bad Request: Content-Type must be application/json.'} return JsonResponse(data, status=400) body = json.loads(request.body) name = body.get('name') price = body.get('price') if name is None or price is None: data = { 'error': 'Bad Request: The key "name" and "price" are required.' } return JsonResponse(data, status=400) try: product = Product(name=name, price=price) product.full_clean() product.save() except ValidationError: data = {'error': 'Bad Request: Bad data.'} return JsonResponse(data, status=400) data = { 'message': 'Successfully Created.', 'result': { 'id': product.id, 'name': product.name, 'price': product.price, } } return JsonResponse(data)
def create(self, validated_data): products = validated_data.pop('products') category = Category.objects.create(**validated_data) # for product in products: # Product.objects.create(category=category, **product) arr = [Product(category=category, **product) for product in products] Product.objects.bulk_create(arr) # BUNCH_SIZE = 500 # for i in range(0, len(arr), BUNCH_SIZE): # Product.objects.bulk_create(arr[i:i+BUNCH_SIZE]) return category
def collect(id): print "collecting product id: %d" % id url = "http://api.macys.com/v3/catalog/product/%d?imagewidth=200" % id request = urllib2.Request(url) request.add_header('X-Macys-Webservice-Client-Id', 'hackathon') request.add_header('Accept', 'application/json') data = opener.open(request).read() obj = json.loads(data) obj = obj['product'][0] try: if 'current' in obj['price']: currentPrice = obj['price']['current']['value'] elif 'sale' in obj['price']: currentPrice = obj['price']['sale']['value'] elif 'regular' in obj['price']: currentPrice = obj['price']['regular']['value'] elif 'original' in obj['price']: currentPrice = obj['price']['regular']['value'] elif 'everydayvalue' in obj['price']: currentPrice = obj['price']['everydayvalue']['value'] product = Product(store_id = obj['id'], title = obj['summary']['name'], desc = obj['summary']['description'], sizes = json.dumps(obj['SizeMap']), colors = json.dumps(obj['colorMap']), images = json.dumps(obj['image']), price = currentPrice, instore_eligible = obj['availability']['instoreeligible'] != 'false' ) product.save() except KeyError as e: print e print "KeyError passing %d" % id return print "done"
class ModelTestCase(TestCase): '''Clase para las pruebas de los modelos''' def setUp(self): '''Definir un producto''' self.name = "Prueba de creación de productos" self.tags = ProductTags(name='nuevo') self.brand = Brand(name='Nike') self.brand.save() self.producto = Product(name='Producto 1', description='Producto de prueba 1', brand=self.brand) def test_puede_crear_producto(self): '''Prueba la creacion del modelo producto''' cantidad_productos_antes = Product.objects.count() self.producto.save() self.tags.save() self.producto.tags.add(self.tags) self.producto.save() cantidad_productos_despues = Product.objects.count() self.assertNotEqual(cantidad_productos_antes, cantidad_productos_despues)
def update_all(json_str): try: data = json.loads(json_str) except JSONDecodeError: return Response({'error': 'Malformed JSON provided'}, status.HTTP_400_BAD_REQUEST) for collection in data: collect_name = collection.get('collection', '').strip() prod_size = int(collection.get('size', 0)) collect_products = collection.get('products', []) if collect_name == '' or prod_size == 0: return Response({'error': 'Wrong JSON structure'}, status.HTTP_400_BAD_REQUEST) collect = Collection(collection=collect_name) collect.save() for product in collect_products: prod_name = product.get('name', '').strip() prod_image = product.get('image', '').strip() prod_sku = product.get('sku', '').strip() if prod_name == '' or prod_image == '' or prod_sku == '': return Response({'error': 'Wrong JSON structure'}, status.HTTP_400_BAD_REQUEST) prod = Product(sku=prod_sku, name=prod_name, image=prod_image, size=prod_size, collection=collect) prod.save() return Response(status=status.HTTP_201_CREATED)
def signup(request): # decoder body = request.body.decode('utf-8') print(request.GET['a']) print(type(request.GET['a'])) print(json.loads(body)) product = Product(**json.loads(body)) # print(request.POST['name']) # print(type(request.POST['name'])) print(product.name) # product.save() return HttpResponse(status=201)
def post(self, request): for product in Product.objects.all(): product.delete() for product in request.data["products"]: if "header" in product and "domainManager" in product and "objectClass" in product and "serialNumber" in product and "location" in product and "currentAmount" in product: header = product["header"] domainManager = product["domainManager"] objectClass = product["objectClass"] serialNumber = product["serialNumber"] location = product["location"] currentAmount = product["currentAmount"] filtered_products = Product.objects.filter( domainManager=domainManager, serialNumber=serialNumber, objectClass=objectClass) if not filtered_products: new_id = int( hashlib.sha1("".join( map(str, [domainManager, objectClass, serialNumber ])).encode()).hexdigest(), 16) #short_id = int(new_id/math.pow(10, 32)) short_id = new_id % 2**31 print(short_id) new_product = Product(id=short_id, header=header, domainManager=domainManager, serialNumber=serialNumber, objectClass=objectClass, location=location, currentAmount=currentAmount) new_product.save() print(filtered_products) response_dict = {"Success": True} return Response(response_dict)
def setUpTestData(cls): cls.product1 = Product(name="iWatch", price=399.99, manufacturer="Apple", product_type="Smartwatch") cls.product1.save() cls.product2 = Product(name="Logitech MX Mouse", price=99.99, manufacturer="Logitech", product_type="Mouse") cls.product2.save() cls.product3 = Product(name="HP Laptop", price=1299.99, manufacturer="HP", product_type="Laptop") cls.product3.save() cls.attribute1 = Attribute(type="Color", value="Red") cls.attribute1.save() cls.attribute2 = Attribute(type="Number Of Wheels", value="4") cls.attribute2.save() cls.attribute3 = Attribute(type="Backup camera", value="false") cls.attribute3.save() pass
def disabled_test_puede_patch_producto(self): self.tags = ProductTags(name='nuevo') self.tags.save() self.brand = Brand(name='Nike') self.brand.save() self.producto = Product(name='Producto 1', description='Producto de prueba 1', brand=self.brand) self.producto.save() self.producto.tags.add(self.tags) self.producto.save() data = json.dumps({ "id": self.producto.pk, "name": "Producto nombre nuevo", "description": "Modificada", "brand": "1" }) response = self.client.patch(reverse('api:update-partial', kwargs={'pk': self.producto.pk}), data=data, content_type='application/json') producto_nuevo = Product.objects.get(pk=self.producto.pk) self.assertEqual(producto_nuevo.name, 'Producto nombre nuevo') self.assertContains(response, 'Producto modificado satisfactoriamente')
def get(self, request, *args, **kwargs): if not Product.objects.all() or not Product.objects.all(): with open(settings.JSON_FILE) as f: dict_data = json.load(f) str_data = json.dumps(dict_data, ensure_ascii=False) shop_names = [] # Get the first shop first_split = str_data.split('{"') second_split = first_split[1].split('": [') first_shop = second_split[0] shop_names.append(first_shop) # Loop to get all the shop names and save to the database shops_split = str_data.split('"}], "') for shop in shops_split: head, sep, tail = shop.partition('"') if len(head) > 2: shop_names.append(head) for shop_name in shop_names: shop_db = Shop() shop_db.title = shop_name shop_db.save() print('Shop saved: ' + str(shop_db.title)) for product in dict_data[shop_name]: product_db = Product() product_db.shop_name = shop_db product_db.title = product['title'] product_db.link = product['link'] product_db.description = product['description'] product_db.image_link = product['image_link'] product_db.save() print('Product saved: ' + str(product_db.title)) return Response('Database migrated') else: return Response('Error')
def main(): with open('products.json') as json_file: data = json.load(json_file) products = data['products'] cats = [] for prod in products: if prod['category'] not in cats: cats.append(prod['category']) for c in cats: dbcat = Category() dbcat.title = c dbcat.save() for prod in products: dbprod = Product() dbprod.name = prod['name'] dbprod.description = prod['description'] dbprod.filename = prod['filename'] dbprod.price = prod['price'] dbprod.category = Category.objects.get(title=prod['category']) dbprod.save()
def main(): with open('products.json') as json_file: data = json.load(json_file) products = data['products'] cats = [] for prod in products: if prod["category"] in cats: dbcat = Category.objects.get(title=prod["category"]) print('skip') else: dbcat = Category() dbcat.title = prod["category"] dbcat.save() cats.append(dbcat.title) dbprod = Product() dbprod.category = dbcat dbprod.name = prod["name"] dbprod.description = prod["description"] dbprod.price = prod["price"] dbprod.filename = prod["filename"] dbprod.save()