示例#1
0
def update_oss_table():
    # Fetch all distinct vendor, product tuples from the main table.
    unique_products = db.session.query(Cpe.vendor, Cpe.product)
    unique_products = unique_products.select_from(
        join(Nvd, Cpe).outerjoin(Vulnerability,
                                 Vulnerability.cve_id == Nvd.cve_id))
    unique_products = unique_products.filter(Vulnerability.cve_id.isnot(None))
    unique_products = unique_products.distinct(Cpe.vendor, Cpe.product)
    # Fetch only entries which are not already contained in OpenSourceProducts.
    unique_products = unique_products.outerjoin(
        Product,
        and_(Cpe.vendor == Product.vendor, Cpe.product == Product.product))
    unique_products = unique_products.filter(Product.vendor.is_(None))
    dump_query(unique_products)

    # We don't do any updates for now.
    created = 0
    for entry in unique_products:
        new_entry = Product(vendor=entry.vendor,
                            product=entry.product,
                            is_open_source=True)
        db.session.add(new_entry)
        sys.stdout.write(".")
        sys.stdout.flush()
        created += 1
    db.session.commit()
    print("")
    sys.stdout.write("created(")
    write_highlighted(created, Fore.GREEN, False)
    sys.stdout.write(")")
示例#2
0
def displayfunc(request):
    pro1 = Product(
        title="Float Recliner",
        price_reg="Rs 750/month",
        description=
        "Rent our Float, a neutral fabric recliner, which merges seamlessly with any decor in your home.",
        qauntity=8,
        image="ridada",
        weight=40,
        depth=90,
        width=80,
        height=110,
        price_sale="Rs 550/month",
        bestseller="yes",
        status="available",
        productlink="/sofa/bcde/",
        category="sofa")

    pro = User(name="Rishab",
               email="*****@*****.**",
               password="******",
               number=9971775086,
               pincode=110032,
               city="Delhi",
               address="1/757 West rohtash nagar shahdara",
               state="Delhi")

    # Product.objects.all().delete()
    # for xyz in range(1,20):
    #    Product.objects.filter(id=xyz).delete()
    design = ""

    # design ='Printing all Dreamreal entries in the DB : <br>'
    # a = Product.objects.get(title="Dhyanachand Bed (Brown)")
    # design +=a.price_sale + "<br>"
    # list1=["1000","899","899","800","750","750",]
    # i=0
    b = User.objects.get(email="*****@*****.**")
    c = b.id

    objects = UserPurchase.objects.filter(email=c)
    for a in objects:
        # xyz.price_reg=list1[i]
        design += a.productid + "<br>"

    # objects = TestModels.objects.all()
    # for xyz in objects:
    #     p=xyz.price
    #     p= str(p)
    #     p = p + "<br>"
    #     design += p
    return HttpResponse(design)
示例#3
0
    def post(self):
        if not self._check_params():
            raise AppException(ret_msg='missing some parameters')

        if self.request_body['type'] == 'product' and self.request_body[
                'action'] == 'add':
            try:
                for items in self.request_body['data']:
                    products = Product(**items)
                    self.sessions.add(products)
                    self.sessions.commit()
            except Exception as e:
                raise AppException(ret_msg='failed, exception: %s' %
                                   e.__str__())
            self.jsonify(ret_msg=u"success")

        if self.request_body['type'] == 'product' and self.request_body[
                'action'] == 'query':
            result = []
            if isinstance(self.request_body['data'], unicode):
                for items in self.sessions.query(Product).all():
                    result.append({
                        'f_id': items.f_id,
                        'f_name': items.f_name,
                        'f_description': items.f_description
                    })

            if isinstance(self.request_body['data'], list):
                for items in self.request_body['data']:
                    tmp = None
                    if items.has_key('f_id'):
                        tmp = self.sessions.query(Product).filter(
                            Product.f_id == int(items['f_id'])).one_or_none()

                    if items.has_key('f_name'):
                        tmp = self.sessions.query(Product).filter(
                            Product.f_name == items['f_name']).one_or_none()
                    if tmp:
                        result.append({
                            'f_id': tmp.f_id,
                            'f_name': tmp.f_name,
                            'f_description': tmp.f_description
                        })

            self.jsonify(ret_msg=u"success", data=result)

        if self.request_body['type'] == 'product':
            raise AppException(ret_msg=u'unsupported action')

        raise AppException(ret_msg=u'type error')
示例#4
0
def __process_request(user):
    parser = FormParser()
    parser.discover_values()
    code = parser.get_value("code", "")
    descr = parser.get_value("descr", "")
    price = parser.get_value("price", "")
    if __validate_properties(code, descr, price):
        return False
    else:
        product = Product(0, user.user_id, code, current_date(), \
        descr, float(price) if is_float(price) else 0)

        conn = Connection()
        if not conn.create_product(product):
            __ERRORS[constants.VALIDATION_ERROR] = conn.errors()
            return False
    return True
示例#5
0
 def fetch_products_by_user_id(self, user_id):
     """Fetch all products from a specic user"""
     self.__open_connection()
     cursor = self.__db.cursor()
     result = []
     try:
         sql_query = """select code,descr,price,entry_date,image_path from product where user_id = %s"""
         cursor.execute(sql_query, (user_id, ))
         query = cursor.fetchall()
         for code, descr, price, entry_date, image_path in query:
             result.append(
                 Product(0, 0, code, entry_date, descr, float(price),
                         image_path))
     except mariadb.Error as error:
         self.__log(self.__default_sql_error, error)
     finally:
         self.__close_connection(cursor)
     return result
示例#6
0
    def test_get_stock_item_returns_stock_item(self):
        repo = StockRepository(DatabaseManager())

        db_product = Product(name="iPhone X", description="Apple iPhone\nwith FaceID", target_stock=3)
        db_product.save()

        db_stock = StockItem(location="A3", quantity=4, product=db_product)
        db_stock.save()

        expected = StockItemDalModel(db_stock.id, db_stock.location, db_stock.quantity, db_product.id)
        expected.product = ProductDalModel(db_product.id, db_product.name,
                                           db_product.description, db_product.target_stock)

        # Act
        stock_item: StockItemDalModel = repo.get_stock_item(db_stock.id)

        # Assert
        self.assertEqual(stock_item, expected)
示例#7
0
def update_products(
    vuln: "data.models.Vulnerability", products: List[Dict[str, str]] = None
) -> Optional[List["data.models.Product"]]:
    # avoid circular imports
    # pylint: disable=import-outside-toplevel
    from data.database import db
    from data.models import Product, Cpe

    # pylint: enable=import-outside-toplevel

    if products is None:
        products = request.form.get("products")

    if isinstance(products, str):
        try:
            products = json.loads(products)
        except (TypeError, json.JSONDecodeError) as ex:
            raise InvalidProducts("Invalid products") from ex

    if products is not None:
        if not isinstance(products, list) or any(
            (not isinstance(p, dict) or "product" not in p or "vendor" not in p)
            for p in products
        ):
            raise InvalidProducts("Invalid products")

        vuln.products = []  # type: ignore
        for product in products:
            if not db.session.query(
                Cpe.query.filter_by(
                    vendor=product["vendor"], product=product["product"]
                ).exists()
            ).scalar():
                raise InvalidProducts(
                    "Invalid product {vendor}/{product}".format(**product)
                )
            prod_obj = Product.query.filter_by(
                vendor=product["vendor"], product=product["product"]
            ).one_or_none()
            if not prod_obj:
                prod_obj = Product(vendor=product["vendor"], product=product["product"])
            vuln.products.append(prod_obj)
        return vuln.products
    return None
def product_view(request):
    if request.method == 'POST':
        form = NewProductForm(request.POST)
        print("errors in create/views.py")
        print(form.errors)
        print(form.non_field_errors)
        if form.is_valid():
            cform = form.cleaned_data
            print(cform)
            new_product = Product(product_name=cform['product_name'],
                                  product_description=cform['product_desc'],
                                  price=cform['price'],
                                  genre=cform['genre'],
                                  release_date=cform['release_date'],
                                  stock=cform['stock'],
                                  merchant_id=cform['merchant_id'],
                                  developer_id=cform['developer_id'])
            new_product.save()

            return redirect('/search/product/' + str(new_product.id))
    else:
        form = NewProductForm()
    context = {'form': form, 'is_logged_in': True}
    return render(request, 'create/newProduct.html', context)
示例#9
0
    def post(self):
        if self.request_body['type'] == 'history' and self.request_body[
            'action'] == 'add':
            try:
                for items in self.request_body['data']:
                    products = Product(**items)
                    self.sessions.add(products)
                    self.sessions.commit()
            except Exception as e:
                raise AppException(
                    ret_msg='failed, exception: %s' % e.__str__())
            self.jsonify(ret_msg=u"success")

        if self.request_body['type'] == 'history' and self.request_body[
            'action'] == 'query':
            result = []
            if self.request_body.has_key('sort'):
                sort = self.request_body['sort']
                if sort == 'f_id':
                    sorts = ConfigHistory.f_id
                elif sort == 'f_create_time':
                    sorts = ConfigHistory.f_create_time
                elif sort == 'f_name':
                    sorts = Product.f_name
                else:
                    sorts = ConfigHistory.f_id

                if self.request_body.has_key('order'):
                    order = self.request_body['order']
                    if order == 'desc':
                        sorts = desc(sorts)
                    else:
                        sorts = asc(sorts)

            if self.request_body.has_key('search'):
                search = self.request_body['search']


                total_record = self.sessions.query(ConfigHistory,
                                                   Product.f_name).join(
                    Product).filter(Product.f_name.like('%'+'%s' %(search) +'%')).order_by(sorts)
            else:
                total_record = self.sessions.query(ConfigHistory,
                                                   Product.f_name).join(
                    Product).order_by(sorts)

            total = total_record.count()
            for items in total_record.limit(
                    self.request_body['limit']).offset(
                self.request_body['offset']):
                result.append({'f_id': items[0].f_id,
                               'f_create_time': items[
                                   0].f_create_time.__str__(),
                               'f_name': items[1],
                               'f_config': items[0].f_config,
                               'f_description': items[0].f_description})
            self.jsonify(ret_msg=u"success", total=total, data=result)
        else:
            raise AppException(ret_msg=u'args error')

        if self.request_body['type'] == 'product':
            raise AppException(ret_msg=u'unsupported action')

        raise AppException(ret_msg=u'type error')