def POST(self, id=None, outputs=None, **kwargs): if id is None: metadata = self.parse_json_dict(simplejson.load(cherrypy.request.body)) for inp in metadata.get("inputs",[]): if '_id' in inp: inp['_id'] = self.parse_value(inp['_id']) id = Transformations.insert_one(metadata).inserted_id for inp in metadata.get("inputs",[]): Products.update_one({'_id':inp['_id']},{'$push':{'transformations':{'_id':id}}}) return self.build_response('ok', **dict(transformation={'_id':id})) else: if outputs == 'outputs': metadata = self.parse_json_dict(simplejson.load(cherrypy.request.body)) resp = simplejson.loads(ProductsController().POST(id=None, metadata=metadata)) if resp['status'] != 'ok': return self.build_response('error', message='error creating output product: %s' % resp['message']) Transformations.update_one({'_id':ObjectId(id)},{'$push':{'outputs':{'_id':ObjectId(resp['data']['product']['_id'])}}}) return self.build_response('ok', **dict(product=resp['data']['product'])) else: return self.build_response('error',message='cannot POST metadata for an existing transformation. Use PUT instead.')
class ProductsViews(Resource, Products): """docstring for Orders""" def __init__(self): self.ops = Products() def get(self): orders = self.ops.getorders() return make_response( jsonify({ 'Status': "Ok", 'Message': "Success", 'My Products': orders }), 200) def post(self): data = request.get_json() name = data['name'] price = data['price'] quantity = data['quantity'] result = self.ops.save(name, price, quantity) return make_response( jsonify({ 'Message': 'Success', 'status': 'ok', 'Payload': result }), 201)
def seed_products(self, quantity): self.product_features_list() i = 0 while i < quantity: weight = random.randint(1, 100) width = random.randint(1, 100) depth = random.randint(1, 100) height = random.randint(1, 100) title = random.choice(self.title_list) description = random.choice(self.title_desc_list) price = float(random.randint(500, 3000)) discount = random.randint(0, 80) image_name = random.choice(self.images_list) category = Category.objects( title=random.choice(self.category_db_list))[0] product = Products(title=title, description=description, price=price, discount=discount, category=category, attributes=ProductAttributes(weight=weight, width=width, depth=depth, height=height)) with open(image_name, 'rb') as image_file: product.image.put(image_file, content_type='image/jpeg') product.save() i += 1
def add_new_product(): body = json.loads(request.data) name = body.get('name', None) if name is None: return jsonify({'error': 'name cannot be null'}) description = body.get('description', None) imageLocation = body.get('imageLocation', None) price = body.get('price', None) discount = body.get('discount', None) new_product = Products(name=name, description=description, imageLocation=imageLocation, price=price, discount=discount) db.add(new_product) #add relations shop_key = body.get('shop_key', None) if shop_key is not None: shop = db.query(Shops).by_key(shop_key) if shop is not None: db.add(product_graph.relation(new_product, Shop_Relation(), shop)) category_key = body.get('category_key', None) if category_key is not None: category = db.query(Categories).by_key(category_key) if category is not None: db.add( product_graph.relation(relation_from=category, relation=Shop_Relation(), relation_to=new_product)) return jsonify({'result': new_product._dump()})
def put(self, prod_id=None): if not prod_id: return "Відсутній id в url" json_data = json.dumps(request.json) try: try: products_data = ProductsSchema().loads(json_data) products_data = json.loads( ProductsSchema().dumps(products_data)) products = Products(id=prod_id) category = Category.objects.filter( id=products_data['category']) # Наступний if не дозволяє переміщати товари в категорії, лише в підкатегорії if category[0].parent_category: products.update(id=prod_id, in_stock=products_data['in_stock'], category=category[0].id, model=products_data['model'], name=products_data['name'], price=products_data['price']) else: products_data = "Продукти не можна переміщати в категорії, лише в підкатегорії" except ValidationError as error: products_data = error.messages return products_data except Val_error as error: data = "Введений ID у невірному форматі або неіснуючий: " + str( error) return data
def post(self): college = self.request.get("college") size = self.request.get("size") color = self.request.get("color") wid = self.request.get("id") i = Products.query(Products.id == wid).get() counter = i.id neck_type = self.request.get("neck_type") sleeve_type = self.request.get("sleeve_type") picture = self.request.get('img') picture = images.resize(picture, 256, 256) token = self.request.get("current_user") logged = Accounts.query(Accounts.tokens == token).get() id = id_generator() current_account = {"logged": logged} product = Products(college=college, size=size, color=color, counter=counter, neck_type=neck_type, sleeve_type=sleeve_type, picture=picture, tokens=token, id=id) product.put() self.redirect("/welcome?current_user=" + logged.tokens)
def create_products(request): db.session.query(ShopListsXProducts).delete() db.session.query(Products).delete() db.session.commit() product_a = dict( description="Pasta 500g", image_url="google.com", retailer="PnP", ) product_b = dict( description="Salad 500g", image_url="google.com2", retailer="PnP1", ) product_c = dict( description="Elizabeth lotion 500g", image_url="google.c", retailer="Shoprite", ) for n in [product_a, product_b, product_c]: product = Products(**n) product.save_instance() def teardown(): # clear table after each test. db.session.query(ShopListsXProducts).delete() db.session.query(Products).delete() db.session.commit() request.addfinalizer(teardown) yield
def get(self): confirm_template = \ jinja_current_directory.get_template('templates/confirm.html') id = self.request.get("id") dele = self.request.get("del") d = Products.query(Products.id == dele).get() product = Products.query(Products.id == id).get() logged = Accounts.query(Accounts.tokens == product.tokens).get() dict = {"product": product, "logged": logged, "dele": dele} self.response.write(confirm_template.render(dict))
def create(request): fname = request.POST['name'] str_price = request.POST['price'] fprice = float(str_price) fdescription = request.POST['description'] if (fname is None) or (str_price is None) or (fdescription is None): result = json.dumps({'success': 0, 'message' : 'ERROR!!!!.'}) else: products = Products(name = fname, price = fprice, description = fdescription) products.save() result = json.dumps({'success': 1, 'message' : 'Product successfully created.'}) return HttpResponse(result)
def update_product(): if 'username' not in session: return jsonify({'status': False, 'message': 'Login Required'}) prod_data = request.get_json(force=True) user = Users.objects(user_id=prod_data['user_id']).first() if not user.is_admin and not user.is_seller: return jsonify({ 'status': False, 'message': 'Opearation not permitted' }) elif user.is_admin: product = Products.objects(product_id=prod_data['product_id']).first() if product: product.title = prod_data['title'] product.description = prod_data['description'] product.price = prod_data['price'] product.save() return jsonify({ 'status': True, 'message': 'Item updated by Admin' }) else: return jsonify({ 'status': False, 'message': 'No matching product found to update' }) elif user.is_seller: product = Products.objects(product_id=prod_data['product_id']).first() if product: if product.seller_id == prod_data['user_id']: product.title = prod_data['title'] product.description = prod_data['description'] product.price = prod_data['price'] product.save() return jsonify({ 'status': True, 'message': 'Item updated by Seller' }) else: return jsonify({ 'status': False, 'message': 'Not Permitted because you did not add the product' }) else: return jsonify({ 'status': False, 'message': 'No matching product found to Update' })
def GET(self, id=None, content=None, **kwargs): if id is None: # if 'include' in kwargs: # include = kwargs.pop('include').split(',') # else: # include = [] q = self.process_filter_params(Products.collection, **kwargs) count = q.count() limit = int(kwargs.get('limit', self.DEFAULT_LIMIT)) if limit == 0: q = [] else: q = self.process_pagination_params(q, **kwargs) q = q.sort([('datetime', pymongo.ASCENDING)]) q = list(q) # if 'transformations' in include: # for doc in q: # qt = Transformations.find({'inputs._id':doc['_id']}) # if qt.count() > 0: # doc['transformations'] = list(qt) return self.build_response( 'ok', **{ 'count': count, 'limit': limit, 'offset': int(kwargs.get('offset', 0)), 'products': q }) else: if content == 'content': q = Products.find_one({'_id': ObjectId(id)}) return serve_gzip_file(os.path.join(self.fs_dir, id), q['name'], "application/x-download", "attachment") else: if 'include' in kwargs: include = kwargs.pop('include').split(',') else: include = [] q = Products.find_one({'_id': ObjectId(id)}) if 'transformations' in include: qt = Transformations.find({'inputs._id': q['_id']}) if qt.count() > 0: q['transformations'] = list(qt) return self.build_response('ok', **dict(product=q))
def add_products(request): if request.method == 'GET': return render_to_response('add_products.html',context_instance=RequestContext(request)) else: title = request.POST['title'].strip() content = request.POST['content'].strip() if not title or not content: messages.add_message(request,messages.ERROR,u'标题内容均不能为空') return render_to_response('add_products.html',{"title":title,"content":content},context_instance=RequestContext(request)) owner = User.objects.all()[0] avatar = "http://res.myform.com/05271590.jpg" new_product = Products(owner=owner,avatar=avatar,title=title,content=content) new_product.save() messages.add_message(request,messages.INFO,u"成功发布产品!") return redirect(reverse("product_list"))
def GET(self, id=None, content=None, **kwargs): if id is None: # if 'include' in kwargs: # include = kwargs.pop('include').split(',') # else: # include = [] q = self.process_filter_params(Products.collection, **kwargs) count = q.count() limit = int(kwargs.get('limit',self.DEFAULT_LIMIT)) if limit == 0: q = [] else: q = self.process_pagination_params(q, **kwargs) q = q.sort([('datetime',pymongo.ASCENDING)]) q = list(q) # if 'transformations' in include: # for doc in q: # qt = Transformations.find({'inputs._id':doc['_id']}) # if qt.count() > 0: # doc['transformations'] = list(qt) return self.build_response('ok', **{ 'count': count, 'limit': limit, 'offset': int(kwargs.get('offset',0)), 'products': q }) else: if content == 'content': q = Products.find_one({'_id':ObjectId(id)}) return serve_gzip_file(os.path.join(self.fs_dir,id), q['name'], "application/x-download", "attachment") else: if 'include' in kwargs: include = kwargs.pop('include').split(',') else: include = [] q = Products.find_one({'_id':ObjectId(id)}) # if 'transformations' in include: # qt = Transformations.find({'inputs._id':q['_id']}) # if qt.count() > 0: # q['transformations'] = list(qt) return self.build_response('ok', **dict(product=q))
def POST(self, id=None, outputs=None, **kwargs): if id is None: metadata = self.parse_json_dict( simplejson.load(cherrypy.request.body)) for inp in metadata.get("inputs", []): if '_id' in inp: inp['_id'] = self.parse_value(inp['_id']) id = Transformations.insert_one(metadata).inserted_id for inp in metadata.get("inputs", []): Products.update_one( {'_id': inp['_id']}, {'$push': { 'transformations': { '_id': id } }}) return self.build_response('ok', **dict(transformation={'_id': id})) else: if outputs == 'outputs': metadata = self.parse_json_dict( simplejson.load(cherrypy.request.body)) resp = simplejson.loads(ProductsController().POST( id=None, metadata=metadata)) if resp['status'] != 'ok': return self.build_response( 'error', message='error creating output product: %s' % resp['message']) Transformations.update_one({'_id': ObjectId(id)}, { '$push': { 'outputs': { '_id': ObjectId(resp['data']['product']['_id']) } } }) return self.build_response( 'ok', **dict(product=resp['data']['product'])) else: return self.build_response( 'error', message= 'cannot POST metadata for an existing transformation. Use PUT instead.' )
def bill_post(): try: session = sessionmaker(bind=engine)() sender_id = request.json['sender_id'] receiver_id = request.json['receiver_id'] products = request.json['products'] bill = BillsWithoutNumber(date=datetime.datetime.now(), sender_id=sender_id, receiver_id=receiver_id) session.add(bill) session.flush() products = [ Products( bill_id=bill.id, quantity=product['quantity'], description=product['description'], unitary_price=product['unitary_price'], ) for product in products ] for product in products: session.add(product) session.flush() session.commit() except Exception: abort(400) return bill_get(bill.id)
def delete(self, prod_id=None): if not prod_id: return "Відсутній id в url" try: product_to_delete = Products.objects.get(id=prod_id) product_to_delete = ProductsSchema().dump(product_to_delete) product = Products(id=prod_id) product.delete() return product_to_delete except DoesNotExist as error: data = "За введеним ID наразі немає записів: " + str(error) return data except Val_error as error: data = "Введений ID у невірному форматі: " + str(error) return data
def fill_db_from_categories(cat): for index, value in enumerate(cat): temp_var = "var" + str(index) temp_var = requests.get( "https://fr.openfoodfacts.org/cgi/search.pl?action=process&tagtype_0=labels&tag_contains_0=contains&tag_0=sans%20gluten&tagtype_1=categories&tag_contains_1=contains&tag_1={}&sort_by=unique_scans_n&page_size=100&axis_x=energy&axis_y=products_n&action=display&json=1" .format(value)).json() for x, i in enumerate(temp_var['products']): single_brand = re.findall("^([^,]*)", str(i['brands'])) try: x = Products.create(product_name=i['product_name_fr'], brands=str(single_brand), description=i['generic_name_fr'], product_url=i['url'], product_code=i['code'], product_image=i['image_ingredients_url'], nutriscore=i['nutrition_grades'], stores=i['stores_tags'], quantity=i['quantity'], category_id=index + 1) x.save() except KeyError as e: print(e)
def POST(self, id=None, content=None, metadata=None, **kwargs): if id is None: if metadata is None: metadata = self.parse_json_dict(simplejson.load(cherrypy.request.body)) metadata['content_length'] = 0 id = Products.insert_one(metadata).inserted_id return self.build_response('ok',**dict(product={'_id':id})) else: if content == 'content': size = self.upload_file(id) Products.update_one({'_id': ObjectId(id)},{'$set':{'content_length':size}}) return self.build_response('ok',**dict(product={'_id':id})) else: return self.build_response('error',message='cannot POST metadata for an existing product. Use PUT instead.')
def get(self): market_template = \ jinja_current_directory.get_template('templates/new_market.html') size = self.request.get("size_") color = self.request.get("color_") neck_type = self.request.get("neck_type_") sleeve_type = self.request.get("sleeve_type_") college = self.request.get("college_") q = Products.query() if size != "Any": q = q.filter(size == Products.size) if color != "Any": q = q.filter(color == Products.color) if neck_type != "Any": q = q.filter(neck_type == Products.neck_type) if sleeve_type != "Any": q = q.filter(sleeve_type == Products.sleeve_type) if college != "Any": q = q.filter(college == Products.college) q = q.fetch() for i in q: if i.counter == "": self.response.out.write( '<form method="post"> <input type="image" name="tag" value="%s" src="/img?img_id=%s" border="0" alt="submit"/></form> <style> form{ display:inline-block;} </style> ' % (i.id, i.key.urlsafe())) self.response.write(market_template.render())
def get(self): market_template = \ jinja_current_directory.get_template('templates/marketplace.html') token = self.request.get("current_user") items = Products.query().filter(Products.counter == "").fetch() dict = {"items": items, "token": token} self.response.write(market_template.render(dict))
def prods_add(manufac_name): context = base_context() has_product = False if request.method == 'POST': barcode = request.form['barcode'] price = request.form['price'] vat_price = request.form['vat_price'] selling_price = request.form['selling_price'] manufac = request.form['manufac'] has_product = db.session.query(exists().where( Products.barcode == barcode)).scalar() if has_product == False: p = Products(barcode=barcode, price=price, vat_price=vat_price, selling_price=selling_price, manufacturer=manufac) db.session.add(p) db.session.commit() context['manufac'] = manufac_name context['has_product'] = str(has_product) return render_template('prods/add.html', **context) context['manufac'] = manufac_name context['has_product'] = str(has_product) return render_template('prods/add.html', **context)
def prods_add(manufac_name): has_product = False if request.method == 'POST': barcode = request.form['barcode'] price = request.form['price'] vat_price = request.form['vat_price'] selling_price = request.form['selling_price'] manufac = request.form['manufac'] has_product = db.session.query( exists().where(Products.barcode == barcode)).scalar() if has_product == False: p = Products(barcode=barcode, price=price, vat_price=vat_price, selling_price=selling_price, manufacturer=manufac) db.session.add(p) db.session.commit() return render_template('prods/add.html', manufac=manufac_name, OUR_APP_NAME=get_value('OUR_APP_NAME'), SECTION_ITEMS=get_value('SECTION_ITEMS'), has_product=str(has_product)) return render_template('prods/add.html', manufac=manufac_name, OUR_APP_NAME=get_value('OUR_APP_NAME'), SECTION_ITEMS=get_value('SECTION_ITEMS'), has_product=str(has_product))
def productsAllGet(): # POST request if request.method == 'POST': body = request.get_json() missing_item = verify_json(body, 'item', 'description') if missing_item: raise APIException('You need to specify the ' + missing_item, status_code=400) products = Products(item=body['item'], description=body['description'], quantity=body['quantity']) db.session.add(products) db.session.commit() all_products = Products.query.filter().order_by(Products.item) all_products = list(map(lambda e: e.serialize(), all_products)) return jsonify(all_products), 200 # GET request if request.method == 'GET': all_products = Products.query.all() all_products = list(map(lambda e: e.serialize(), all_products)) return jsonify(all_products), 200 return "Invalid Method", 404
def handle_products(): if request.method == 'POST': body = request.get_json() if body is None: raise APIException("You need to specify the request body as a json object", status_code=400) if 'plan_name' not in body: raise APIException('You need to specify the plan_name', status_code=400) # if 'price' not in body: # raise APIException('You need to specify the price', status_code=400) # if 'orders_id' not in body: # raise APIException('You need to specify the orders_id', status_code=400) # if 'mag_f' not in body: # raise APIException('You need to specify the mag_f', status_code=400) # if 'temp' not in body: # raise APIException('You need to specify the temp', status_code=400) # if 'atmo_pressure' not in body: # raise APIException('You need to specify the atmo_pressure', status_code=400) # if 'axis_measure' not in body: # raise APIException('You need to specify the axis_measure', status_code=400) # return "Invalid Method", 404 product1 = Products(plan_name=body['plan_name'], price=body['price']) db.session.add(product1) db.session.commit() return "ok", 200 if request.method == 'GET': all_products = Products.query.all() all_products = list(map(lambda x: x.serialize(), all_products)) return jsonify(all_products), 200
def post(self): token = self.request.get("current_user") logged = Accounts.query(Accounts.tokens == token).get() dele = self.request.get("del") d = Products.query(Products.id == dele).get() d.key.delete() self.redirect('/welcome?current_user=' + logged.tokens)
def post(self): token = self.request.get("current_user") logged = Accounts.query(Accounts.tokens == token).get() id = self.request.get("id") i = product = Products.query(Products.id == id).get() self.redirect("/counterupload?current_user="******"&id=" + i.id)
def db_create_product(name, amount, price): #Here we could also check existence of the product (do not allow duplicate name) if validate_int((amount, price)): new_product = Products(None, name, amount, price) db.session.add(new_product) db.session.commit() return True return False
def get(self): status_template = \ jinja_current_directory.get_template('templates/status.html') token = self.request.get("current_user") logged = Accounts.query(Accounts.tokens == token).get() request = Products.query().filter(Products.tokens == logged.tokens, Products.counter != "").fetch() requests = [] for i in request: requests.append( Products.query().filter(Products.id == i.counter).get()) offers = Products.query().filter(Products.tokens == logged.tokens, Products.counter == "").fetch() dict = {"requests": requests, "offers": offers, "token": token} self.response.write(status_template.render(dict))
def get(self): searchkey = self.request.get("search") search = Products.query().fetch() # searchfiltered = search.filter(product_keywords == searchkey.upper()) # search = Products.query(Products.product_keywords.IN([searchkey.upper()])) # return search search_template = the_jinja_env.get_template("templates/search.html") template_vars = {'searchterm': search, "keyword": searchkey} self.response.write(search_template.render(template_vars))
def __init__(self): self.logger = logging.getLogger('CollectData') try: self.products = pickle.load(open(PRODUCTSFILE, 'rb')) except FileNotFoundError: self.products = Products() XAEvents.instance = self #이벤트 처리 클래스에 현재 인스턴스를 저장 self.session = None #세션 오브젝트 self.query = None #쿼리 오브젝트 self.timer = 0 #타이머 #self.yesterday = (datetime.today() - timedelta(1)).strftime('%Y%m%d') #로그인 self.next_step(0) #dev self.flag = False
def get(self): desc_template = \ jinja_current_directory.get_template('templates/description.html') token = self.request.get("current_user") id = self.request.get("id") wish = Wish.query(Wish.id == id).get() product = Products.query(Products.id == id).get() dict = {"product": product, "wish": wish, "token": token} self.response.write(desc_template.render(dict))
def list_products(): """ Returns all of the Products """ app.logger.info('Request for product list') products = [] category = request.args.get('category') name = request.args.get('name') price = request.args.get('price') if category: products = Products.find_by_category(category) elif name: products = Products.find_by_name(name) elif price: products = Products.find_by_price(price) else: products = Products.all() results = [product.serialize() for product in products] return make_response(jsonify(results), status.HTTP_200_OK)
def post(self): for i in Products.query().fetch(): if i.id == self.request.get("tag"): token = self.request.get("current_user") logged = Accounts.query(Accounts.tokens == token).get() self.redirect("/desc?current_user="******"&id=" + i.id) elif self.request.get("back_btn") == "Go Back": token = self.request.get("current_user") self.redirect("/defmarketplace?current_user=" + token)
def search_items(): prod_id = request.args.get('prod_id') products = json.loads(Products.objects(product_id=prod_id).to_json()) if len(products): return jsonify({'status': True, 'products': products}) else: return jsonify({ 'status': False, 'message': 'The Item is not available.' })
def delete_product(product_id): """ Delete a Product This endpoint will delete a Product based the id specified in the path """ app.logger.info('Request to delete product with id: %s', product_id) product = Products.find(product_id) if product: product.delete() return make_response('', status.HTTP_204_NO_CONTENT)
def GET(self, name=None, **kwargs): if name is not None: if 'distinct' in kwargs: if kwargs['distinct'] == 'type': qq = {} else: qq = {'type':name} q = Products.distinct(kwargs['distinct'], qq) return self.build_response('ok', **{'attribute': kwargs['distinct'], 'values': q}) else: q = ProductTypes.find_one({'name':name}) return self.build_response('ok', **{self.name_singular: q}) else: return super(ProductTypesController, self).GET(name, **kwargs)
def PUT(self, id, **kwargs): metadata = self.parse_json_dict(simplejson.load(cherrypy.request.body)) Products.update_one({'_id':ObjectId(id)}, {'$set':metadata}) return self.build_response('ok',**dict(product={'_id':id}))