def __create_relationship(product: Product, elements: List[str],
                           model_cls: NodeBase,
                           connection_name: str) -> None:
     for element_name in elements:
         if element_name != 'nan':
             connected_object = model_cls.get_or_create(
                 {'name': element_name})[0]
             product.__getattribute__(connection_name).connect(
                 connected_object)
Пример #2
0
 def post(self):
     body = request.get_json()
     user_id = get_jwt_identity()
     user = User.objects.get(id=user_id)
     if not user.privilege:
         return {'error': 'Elevated privilege required'}, 403
     try:
         new_product = Product(**body)
     except ValidationError:
         return {'error': 'Missing required values'}, 400
     else:
         new_product.save()
         id = new_product.id
         return {'id': str(id)}, 200
Пример #3
0
 def get(self):
     user_id = get_jwt_identity()
     user = User.objects.get(id=user_id)
     if not user.privilege:
         return {'error': 'Elevated privilege required'}, 403
     out_stock = extract_basic_info(json.loads(Product.objects(stock=0).to_json()), True)
     return Response(json.dumps(out_stock), mimetype="application/json", status=200)
Пример #4
0
 def post(self):
     """
     Function, to handle POST request to insert/create a product in the db
     """
     try:
         json_input = request.get_json()
         product_obj = Product(**json_input)
         product_obj.save()
         return Response(product_obj.to_json(),
                         mimetype="application/json",
                         status=201)
     except (FieldDoesNotExist, ValidationError):
         raise SchemaValidationError
     except NotUniqueError:
         raise ProductAlreadyExistsError
     except Exception as e:
         raise InternalServerError
Пример #5
0
def add_product():
    body = request.get_json()
    print(body)
    try:
        product = Product(**body).save()
    except NotUniqueError as e:
        raise Exception(e)

    id = product.id
    return {'id': str(id)}, 200
Пример #6
0
def add_product(token):
    data = request.get_json()
    try: 
        product = Product(name=data.get('name'), 
        description=data.get('description'),  
        price=data.get('price'),
        category_id=data.get('category_id')
         )
        product.insert()
        return jsonify({
            'success': True,
            'product': product.format()
        }),200
    except:
        print(sys.exc_info())
        db.session.rollback()
        abort(401)
    finally:
      db.session.close()
Пример #7
0
    def get(self, user_id):
        try:
            products = Product.objects(user=user_id)
            products = [product.to_mongo() for product in products]

            return Response(JSONEncoder().encode(products),
                            mimetype="application/json",
                            status=200)
        except Exception:
            raise InternalServerError
Пример #8
0
 def get(self):
     """
     Function, to handle GET request to extract all available products
     """
     try:
         products_json = Product.objects().to_json()
         return Response(products_json,
                         mimetype="application/json",
                         status=200)
     except Exception:
         raise InternalServerError
Пример #9
0
def get_products_from_query():
    number_per_page = 20
    try:
        page = int(request.args.get('page'))
    except ValueError:
        page = 1
    index = number_per_page * page
    previous_index = index - number_per_page

    query = request.args.get('q')
    categories = request.args.get('categories')
    req = request.args.get('req')
    if req == "products":
        if categories == "all" or categories == "undefined":
            product = (Product.objects(
                name__icontains=query)[previous_index:index].to_json())
            session['num_products'] = len(
                Product.objects(name__icontains=query))
        else:
            product = (Product.objects(
                Q(name__icontains=query)
                & Q(instrument=categories))[previous_index:index].to_json())
            session['num_products'] = len(
                Product.objects(
                    Q(name__icontains=query) & Q(instrument=categories)))
        return Response(product, mimetype="application/json", status=200)
    elif req == "page_info":
        print(session['num_products'])
        pages = ceil(session['num_products'] / number_per_page)
        page_info = [
            json.dumps({
                'number_per_page': number_per_page,
                'page': page,
                'number_of_pages': pages,
                'query': query,
                'categories': categories,
                'num_products': session['num_products']
            })
        ]
        session['page_info'] = json.loads(page_info[0])
        return Response(page_info, mimetype="application/json", status=200)
Пример #10
0
 def get(self):
     user_id = get_jwt_identity()
     user = User.objects.get(id=user_id)
     if not user.privilege:
         return {'error': 'Elevated privilege required'}, 403
     number_customer = User.objects(privilege=False).count()
     number_product = Product.objects().count()
     number_outofstock = Product.objects(stock=0).count()
     number_onsale = Product.objects(discount__ne=0).count()
     number_order = (list(User.objects.aggregate({"$unwind":"$orders"}, {"$count":"number_orders"})))[0]["number_orders"]
     number_belowfive = Product.objects(stock__lte=5).count()
     pipeline=[{"$unwind": "$orders" },{"$unwind": "$orders.cart" },{"$group":{"_id":"$orders.cart.product_id", "quantity":{"$sum": "$orders.cart.quantity"}}}, {"$sort":{"quantity":-1}}]
     result=list(User.objects.aggregate(pipeline))
     sales=[json.loads(Product.objects(id=i["_id"])[0].to_json()) for i in result]
     for i,pro in enumerate(sales):
         pro["stock"]=result[i]["quantity"]
     top_sells = extract_basic_info(sales)
     stats = {'number_customer': number_customer, 'number_product': number_product, 'number_outofstock': number_outofstock, \
             'number_onsale': number_onsale, 'number_order': number_order, 'number_belowfive': number_belowfive, "top_sells":top_sells}
     return Response(json.dumps(stats), mimetype='json/application', status=200)
     
Пример #11
0
    def post(self):
        name = request.json['name']
        company = request.json['company']
        #production_date = request.json['production_date']
        #expiration_date = request.json['expiration_date']
        description = request.json['description']
        qrcode = request.json['qrcode']

        new_product = Product(name,company, description,qrcode)
        db.session.add(new_product)
        db.session.commit()
        return product_schema.dump(new_product)
Пример #12
0
 def post(self):
     body = request.get_json()
     isSortByPrice = False
     isAscending = False
     if body:    
         if body.get('sort') == 'price+':
             isSortByPrice = True
             isAscending = True
         elif body.get('sort') == 'price-':
             isSortByPrice = True
         if body.get('subcategory'):
             subcat = body.get('subcategory')
             if isSortByPrice:
                 if isAscending:
                     subcat_product = extract_basic_info(json.loads(Product.objects(subcategory=subcat).order_by('+price').to_json()))
                 else:
                     subcat_product = extract_basic_info(json.loads(Product.objects(subcategory=subcat).order_by('-price').to_json()))
             else:
                 subcat_product = extract_basic_info(json.loads(Product.objects(subcategory=subcat).to_json()))
             return Response(json_util.dumps(subcat_product), mimetype="json/application", status=200)
     return {'error': 'Subcategory not found/given'}, 401
Пример #13
0
 def get(self, id):
     try:
         item = Product.objects().get(id=id).to_json()
     except DoesNotExist:
         return {'error': 'Product ID not found'}, 404
     else:
          
         if get_jwt_identity():
             user_id=get_jwt_identity()
             if User.objects(id=user_id,recently_viewed=id):
                 User.objects(id=user_id).update_one(pull__recently_viewed=id)
             User.objects(id=user_id).update_one(push__recently_viewed=id)
             # print(User.objects(id=user_id)[0].recently_viewed)
         
         return Response(item, mimetype="application/json", status=200)
Пример #14
0
def new_product(name, description, available_quantities, price, price_in_pack,
                file):
    product = Product(name=name,
                      description=description,
                      available_quantity_mon=available_quantities[0],
                      available_quantity_tue=available_quantities[1],
                      available_quantity_wed=available_quantities[2],
                      available_quantity_thu=available_quantities[3],
                      available_quantity_fri=available_quantities[4],
                      price=price,
                      price_in_pack=price_in_pack)
    db.session.add(product)
    db.session.commit()
    if file:  # on vérifie qu'un fichier a bien été envoyé
        if '.' in file.filename and file.filename.rsplit(
                '.',
                1)[1] in ('png', 'jpg',
                          'jpeg'):  # on vérifie que son extension est valide
            product = find_products()[-1]
            file.save('static/img/product' + str(product.id) + '.' +
                      file.filename.rsplit('.', 1)[1])
            product.image_format = file.filename.rsplit('.', 1)[1]
            db.session.add(product)
            db.session.commit()
Пример #15
0
def get_zzounds_products(path, instrument):
    result = requests.get(path, timeout=15)
    src = result.content
    soup = BeautifulSoup(src, 'html5lib')

    product_objects = soup.find_all("div", class_="product-card")

    products = []
    for product in product_objects:
        link = product.find("a", class_="prod-name")
        text = link.text
        href = link['href']
        img_url = product.find("img", class_="product-img")['src']
        if (product.find("div", class_="price-1")):
            price = product.find("div",
                                 class_="price-1").find("span",
                                                        class_="price").text
        else:
            continue
        regex = r'\S+'
        filtered_price = re.search(regex, price).group(0)
        curr_product = {
            "name": text,
            "instrument": instrument,
            "url": href,
            "image_url": img_url,
            "price": filtered_price
        }
        products.append(curr_product)
        try:
            result = requests.post("http://127.0.0.1:5000/products",
                                   json=curr_product)
        except Exception as e:
            try:
                product_id = Product.objects(name=text).first().id
                print(product_id)
                result = requests.put("http://127.0.0.1:5000/products/" +
                                      str(product_id),
                                      json=curr_product)
            except requests.exceptions.RequestException as e:
                raise SystemExit(e)
        except requests.exceptions.RequestException as e:
            raise SystemExit(e)
    return products
Пример #16
0
    def post(self):
        # get data from request
        body = request.get_json()
        name = body.get("name")
        description = body.get("description")

        if name is None or description is None:
            return _400_product_missing_body_parameter()

        # create product in db
        product = Product(name=name, description=description)
        db.session.add(product)
        try:
            db.session.commit()
        except exc.IntegrityError:  # sql duplicate
            db.session.rollback()
            return _409_product_name_already_exist()

        # register product in offers microservice
        registration = register_product(product_id=product.id,
                                        name=product.name,
                                        description=product.description)

        if registration.status_code != 201:
            # remove product from our db
            db.session.delete(product)
            db.session.commit()
            # send erroneous response
            data = {
                "message": "product couldn't be registered",
                "error": registration.json()["msg"],
            }
            return Response(
                response=json.dumps(data),
                mimetype="application/json",
                status=registration.status_code,
            )

        data = {"message": "product has been created", "id": product.id}
        return Response(response=json.dumps(data),
                        mimetype="application/json",
                        status=201)
Пример #17
0
def add_product():
    try:
        name = request.json['name']
        comment = request.json['comment']
        price = request.json['price']
        category_id = request.json['category_id']

        new_product = Product(name, comment, price, category_id)

        db.session.add(new_product)
        db.session.commit()
    except IntegrityError:
        return jsonify({'IntegrityError': {
            'message': 'This product already exist',
            'status': 400
        }})
    except:
        return jsonify({'InternalServerError': {
            'message': 'Something went wrong',
            'status': 500
        }})
    return product_schema.jsonify(new_product)
    def import_data(self):
        for index, row in self.dataframe.iterrows():
            directors, actors, countries, genres = self.__split_row(
                row, ['director', 'cast', 'country', 'listed_in'])

            product = Product(show_id=row['show_id'],
                              title=row['title'],
                              year=int(row['release_year']),
                              description=row['duration'],
                              duration=row['duration']).save()

            self.__create_relationship(product, directors, Director,
                                       'director')
            self.__create_relationship(product, actors, Actor, 'actor')
            self.__create_relationship(product, countries, Country, 'country')
            self.__create_relationship(product, genres, Genre, 'genre')
            self.__create_relationship(product, [row['rating']], Rating,
                                       'rating')
            self.__create_relationship(product, [row['type']], Type, 'type')

            print(row['title'], 'imported', index, 'of', len(self.dataframe))

        print('Import has finished')
Пример #19
0
    def get(self):
        all_products = Product.objects()
        recently_viewed = extract_basic_info(json.loads(all_products[0:5].to_json()))
        new_arrivals = extract_basic_info(json.loads(all_products[5:10].to_json()))
        today_deals = extract_basic_info(json.loads(Product.objects(discount__gt=0)[:20].to_json()))
        pipeline=[{"$unwind": "$orders" },{"$unwind": "$orders.cart" },{"$group":{"_id":"$orders.cart.product_id", "quantity":{"$sum": "$orders.cart.quantity"}}}, {"$sort":{"quantity":-1}}]
        sales=[json.loads(Product.objects(id=i["_id"])[0].to_json()) for i in list(User.objects.aggregate(pipeline))[:10]]
        
        top_sells = extract_basic_info(sales)
        fresh_vegies = extract_basic_info(json.loads(Product.objects()[0:16].to_json()))
        data = {}
        data['slides'] = list(["https://via.placeholder.com/150", "https://via.placeholder.com/100", "https://via.placeholder.com/200"])
        data['content'] = list([{'title': 'Today\'s Deals', 'content': today_deals}, \
        {'title': 'New Arrivals', 'content': new_arrivals}, {'title': 'Top Sellers', 'content': top_sells}, \
        {'title': 'Veggies', 'content': fresh_vegies}])
        if get_jwt_identity():
            # print([i for i in User.objects(id=get_jwt_identity())[0].recently_viewed])
            recently_viewed=extract_basic_info(([json.loads(Product.objects(id=i)[0].to_json()) for i in User.objects(id=get_jwt_identity())[0].recently_viewed[:-11:-1]]))
            
            data['content'].append({'title': 'Recently Viewed', 'content': recently_viewed})
            recently_viewed=User.objects(id=get_jwt_identity())[0].recently_viewed
            # recently_viewed= map(objectid.ObjectId,recently_viewed)
            recently_viewed=[objectid.ObjectId(i) for i in recently_viewed]
            pipeline=[

                    {"$match":{"_id":{"$in":recently_viewed}}},
                    {"$project": {"_id":0,"subcategory":1}},

            
            ]
            s=[]
            for i in list(Product.objects().aggregate(pipeline)):
                    s=s+i["subcategory"]
            s=list(set(s))
            pipeline=[

                    {"$match":{"subcategory":{"$in":s}}},
                    {"$sample": {"size":20}},

            
            ]
            
            data['content'].append({'title': 'Recommended Products', 'content': extract_basic_info((list(Product.objects().aggregate(pipeline))))[:100]})
        return Response(json_util.dumps(data), mimetype="application/json", status=200)
Пример #20
0
    def load_one_data(self, prod_key, prod_to_load):

        # Insert Product
        if Product.objects.filter(pk=prod_key).exists() is False:
            nut_id = Nutriscore.objects.get(
                nut_type=prod_to_load["nutriscore_grade"][0].upper())
            query = Product(prod_id=prod_key, prod_name=prod_to_load['product_name_fr'],
                            prod_url=prod_to_load['url'], prod_image=prod_to_load['image_small_url'], nut_id=nut_id)
            query.save()
        else:
            pass

        prod_object = Product.objects.get(pk=prod_key)

        # Insert Categories
        for n in range(len(prod_to_load["categories"])):
            # In categorie table
            if Categorie.objects.filter(cat_name=prod_to_load["categories"][n]).exists() is False:
                query = Categorie(cat_name=prod_to_load["categories"][n])
                query.save()

            # In prodcat table
            cat_object = Categorie.objects.get(
                cat_name=prod_to_load["categories"][n])
            cat_id = cat_object.cat_id
            if Prodcat.objects.filter(cat_id=cat_id, prod_id=prod_key).exists() is False:
                query = Prodcat(cat_id=cat_object, prod_id=prod_object)
                query.save()

        # Insert Brand
        for n in range(len(prod_to_load["brands"])):
            # In brand table
            if Brand.objects.filter(brand_name=prod_to_load["brands"][n]).exists() is False:
                query = Brand(brand_name=prod_to_load['brands'][n])
                query.save()

            # In prodbrand table
            brand_object = Brand.objects.get(
                brand_name=prod_to_load["brands"][n])
            brand_id = brand_object.brand_id
            if Prodbrand.objects.filter(brand_id=brand_id, prod_id=prod_key).exists() is False:
                query = Prodbrand(brand_id=brand_object, prod_id=prod_object)
                query.save()

        # Insert Shop
        for n in range(len(prod_to_load["stores"])):
            # In shop table
            if Shop.objects.filter(shop_name=prod_to_load["stores"][n]).exists() is False:
                query = Shop(shop_name=prod_to_load['stores'][n])
                query.save()

            # In prodshop table
            shop_object = Shop.objects.get(
                shop_name=prod_to_load["stores"][n])
            shop_id = shop_object.shop_id
            if Prodshop.objects.filter(shop_id=shop_id, prod_id=prod_key).exists() is False:
                query = Prodshop(shop_id=shop_object, prod_id=prod_object)
                query.save()
Пример #21
0
    def post(self, raw_keyword):
        user_id = get_jwt_identity()
        isAdmin = False
        if user_id:
            user = User.objects.get(id=user_id)
            if user.privilege:
                isAdmin = True

        body = request.get_json()

        isSortByPrice = False
        isAscending = False
        
        match={"$match":{}}
        price_min  = 0
        price_max = 999999
        list_subcategory = []
        if body:    
            if body.get('sort') == 'price+':
                isSortByPrice = True
                isAscending = True
            elif body.get('sort') == 'price-':
                isSortByPrice = True
            else:
                pass
            
            if body.get('price_min'):
                price_min = int(body.get('price_min'))
                match["$match"]["price"]={"$gte":price_min}
            if body.get('price_max'):
                price_max = int(body.get('price_max'))
                match["$match"]["price"]={"$lte":price_max}
            
            if body.get('subcategories'):
                list_subcategory = body.get('subcategories')
                match["$match"]["subcategory"]={"$all":list_subcategory}


        keyword = unquote(raw_keyword)
        pipeline= [  
                    {"$search": {"text": {"query": keyword, "path": ["name","subcategory","description","others.quantity"]}}},
                    
                    {"$sort":{"score"*(1-int(isSortByPrice))+"price"*(int(isSortByPrice)): -1+2*(int(isAscending))}},
                    #{"$project": {"_id":0,"name": 1,"price": 1,"score": { "$meta": "searchScore" }}}
                  ]
        if len(match["$match"])!=0:
            pipeline.insert(1,match)
        print(pipeline)
        matching_products = extract_basic_info((list(Product.objects().aggregate(pipeline))), isAdmin)[:100]
        ids=[str(i["_id"]) for i in matching_products]
       
        if len(matching_products)<10:
                kwargs = dict(name__istartswith=keyword, price__gte=price_min,price__lte=price_max, subcategory__all=list_subcategory)

                p= extract_basic_info( json.loads(Product.objects(**{k: v for k, v in kwargs.items() if v !=  []} ).to_json()), isAdmin)
                
                for i in p[:75]:             
                    if i["_id"]["$oid"] not in ids:
                            matching_products.append(i)
                            ids.append(i["_id"])
        if len(matching_products)<20:
            kwargs = dict(name__icontains=keyword, price__gte=price_min,price__lte=price_max, subcategory__all=list_subcategory)
            p= extract_basic_info( json.loads(Product.objects( **{k: v for k, v in kwargs.items() if v != []}).to_json()), isAdmin)
           
            for i in p[:50]:             
                if i["_id"]["$oid"] not in ids:
                        matching_products.append(i)
                        ids.append(i["_id"])
        if len(matching_products)<30:
            kwargs = dict(description__icontains=keyword, price__gte=price_min,price__lte=price_max, subcategory__all=list_subcategory)
            p= extract_basic_info( json.loads(Product.objects(**{k: v for k, v in kwargs.items() if v != []}).to_json()), isAdmin)
            
            for i in p[:25]:             
                if i["_id"]["$oid"] not in ids:
                        matching_products.append(i)
                        ids.append(i["_id"])
        if isSortByPrice:
            matching_products= sorted(matching_products, key=lambda k: k['price'],reverse=not isAscending) 
        
        
        #matching_products = extract_basic_info(json.loads(Product.objects(name__contains=keyword).to_json()))
        return Response(json_util.dumps(matching_products), mimetype="application/json", status=200)
Пример #22
0
from database.models import Client, Product, Feedback
from collections import Counter

def get_suggested_products(client):
    scores = Counter()
    clients = Client.objects(contact_id__ne=client.contact_id)
    for c in clients:
        sim = len([att for att, val in c.boolean_attributes.items() \
                if client.boolean_attributes[att] == val])
        for f in Feedback.objects(client=c):
            scores[f.product.product_id] += sim if f.positive else -sim
    return sorted(scores.items(), key=lambda e: e[1], reverse=True)


if __name__ == '__main__':
    import database
    database.connect()

    client = Client.objects().first()
    print client.boolean_attributes

    products = get_suggested_products(client)
    print products
    for p_id, score in products:
        p = Product.objects(product_id=p_id).first()
        print p.name.encode('utf-8'), score
Пример #23
0
def test_new_product():
    product = Product(name="Test", description="Test Product")
    assert product.name == "Test"
    assert product.description == "Test Product"
Пример #24
0
def get_group(id):
    group = Product.objects(instrument=id).to_json()
    return Response(group, mimetype="application/json", status=200)
Пример #25
0
def get_product_from_id():
    query = request.args.get('q')
    product = Product.objects(id=query).to_json()
    return Response(product, mimetype="application/json", status=200)