예제 #1
0
def update_product():
    new_product = Product()
    new_product.name = request.form['name']
    new_product.description = request.form['description']
    db.session.query(Product).filter_by(name=new_product.name).update({"description" : new_product.description})
    db.session.commit()
    return product_schema.jsonify(new_product)
예제 #2
0
def add_product():
    new_product = Product()
    new_product.name = request.form['name']
    new_product.description = request.form['description']
    db.session.add(new_product)
    db.session.commit()
    return product_schema.jsonify(new_product)
예제 #3
0
def Addproduct(request):
    form=ProductForm(request.POST or None)
    if form.is_valid():
        ModelName = form.cleaned_data['ModelName']
        description = form.cleaned_data['description']
        photo = form.cleaned_data['photo']
        manufacturer = form.cleaned_data['manufacturer']
        price_in_dollars = form.cleaned_data['price_in_dollars']
        Quantity = form.cleaned_data['Quantity']
        Serial_No =form.cleaned_data['Serial_No']
        product=Product()
        product.ModelName=ModelName
        product.description=description
        product.photo=photo
        product.manufacturer=manufacturer
        product.price_in_dollars=price_in_dollars
        product.Quantity=Quantity
        product.Serial_No=Serial_No  
        product.save()
        return HttpResponseRedirect(reverse('ecom:product'))
        
        
        #return HttpResponseRedirect(reverse('ecom:product'))
    else:
        return render(request,"ItemMaster.html",{"form":form})    
예제 #4
0
def createProduct():
    ''' Function to create a new product model
        Method : Post
    '''

    newProduct = Product()

    #   Get product info from request
    newProduct.product_name = request.form.get('productName')
    newProduct.seller_id = request.form.get('sellerId')
    newProduct.price = request.form.get('price')
    newProduct.place = request.form.get('place')
    newProduct.description = request.form.get('description')

    #   assign create and modify date to current date time
    newProduct.create_date = datetime.datetime.now()
    newProduct.modify_date = datetime.datetime.now()

    #   save to db
    try:
        db.session.add(newProduct)
        db.session.commit()

        return make_response(jsonify(newProduct.serialize()), 200)

    except Exception as e:
        return make_response(str(e), 500)
    def process_item(self, item, spider):

        # Check if the Product already exists
        product = (self.session.query(Product).filter_by(
            store=item["store"], sku=item["sku"]).first())

        if product is None:
            product = Product(store=item["store"], sku=item["sku"])

        product.barcodes = item["barcodes"]
        product.brand = item["brand"]
        product.name = item["name"]
        product.description = item["description"]
        product.image_url = item["image_url"]

        self.session.add(product)
        self.session.commit()

        # Check if the BranchProduct already exists
        branch_product = (self.session.query(BranchProduct).filter_by(
            product=product, branch=item["branch"]).first())

        if branch_product is None:
            branch_product = BranchProduct(product=product,
                                           branch=item["branch"])

        branch_product.stock = item["stock"]
        branch_product.price = item["price"]

        self.session.add(branch_product)
        self.session.commit()

        return item
예제 #6
0
def create(request, keyname):
    "Backdoor to create a new entity"
    u = auth.get_current_user(request)
    if u.is_admin:
        p = Product(key_name=keyname)
        p.name = "New Product"
        p.description = "The description"        
        p.put()
        return HttpResponseRedirect(reverse('store-edit', args=(p.key(),)))
    return HttpResponseRedirect(reverse('store-index'))
예제 #7
0
def add_product():
    new_product = Product()
    new_product.name = request.get_json()["name"]
    new_product.description = request.get_json()["description"]
    #import pdb;pdb.set_trace()
    #for key, value in request.get_json().items():
    #    if value != None:
    #        new_product.key = value
    db.session.add(new_product)
    db.session.commit()
    return '', 201
예제 #8
0
def products():
    if request.method == 'GET':
        products = db.session.query(Product).all()
        return render_template('home.html', products=products)
    else:
        new_product = Product()
        new_product.name = request.json["name"]
        new_product.description = request.json["description"]
        db.session.add(new_product)
        db.session.commit()
        return product_schema.jsonify(new_product)
예제 #9
0
def create_product_with_event_type(
        event_name='Test event',
        event_type=EventType.SPECTACLE_VIVANT,
        description=None,
        dominant_color=None,
        duration_minutes=60,
        is_national=False,
        thumb_count=0,
) -> Product:
    product = Product()
    product.name = event_name
    product.description = description
    product.durationMinutes = duration_minutes
    product.thumbCount = thumb_count
    product.isNational = is_national
    product.type = str(event_type)
    product.firstThumbDominantColor = dominant_color
    if product.thumbCount > 0 and not dominant_color:
        product.firstThumbDominantColor = b'\x00\x00\x00'
    product.description = description
    return product
예제 #10
0
def fetch_category(search_index, amazon_node_id):
    api = caching.ResponseCachingAPI(settings.AMAZON_AWS_KEY,
                                     settings.AMAZON_SECRET_KEY,
                                     settings.AMAZON_API_LOCALE,
                                     settings.AMAZON_ASSOCIATE_TAG,
                                     cachedir='cache',
                                     cachetime=86400)

    try:
        for root in api.item_search(
                search_index,
                BrowseNode=str(amazon_node_id),
                ResponseGroup=settings.AMAZON_RESPONSE_GROUP):

            for item in root.Items.Item:
                product = Product()
                product.category = Category.objects.get(
                    amazon_node_id=amazon_node_id)
                product.asin = item.ASIN
                product.title = unicode(item.ItemAttributes.Title)
                product.detailpageurl = unicode(item.DetailPageURL)
                product.manufacturer = unicode(
                    getattr(item.ItemAttributes, 'Manufacturer', None))
                product.publisher = unicode(
                    getattr(item.ItemAttributes, 'Publisher', None))
                product.brand = unicode(
                    getattr(item.ItemAttributes, 'Brand', None))
                product.popularity = getattr(item, 'SalesRank', 1000)
                if hasattr(item, 'MediumImage'):
                    product.medium_image = getattr(item.MediumImage, 'URL',
                                                   None)
                if hasattr(item, 'LargeImage'):
                    product.large_image = getattr(item.LargeImage, 'URL', None)
                if hasattr(item, 'EditorialReviews'):
                    product.description = unicode(
                        getattr(item.EditorialReviews.EditorialReview,
                                'Content', None))
                if hasattr(item.Offers, 'Offer'):
                    product.price = item.Offers.Offer.OfferListing.Price.FormattedPrice.pyval
                elif hasattr(item.ItemAttributes, 'ListPrice'):
                    product.price = item.ItemAttributes.ListPrice.FormattedPrice.pyval
                elif hasattr(item.OfferSummary, 'LowestUsedPrice'):
                    product.price = u'used from %s' % item.OfferSummary.LowestUsedPrice.FormattedPrice.pyval
                else:
                    product.price = None
                product.save()

    except AWSError, e:
        if e.code == 'AWS.ParameterOutOfRange':
            pass  # reached the api limit of 10 pages
        else:
            raise ValidationError(message=e.msg)
예제 #11
0
def products():
    if request.method=="GET":
        products = db.session.query(Product).all() # SQLAlchemy request => 'SELECT * FROM products'
        return products_schema.jsonify(products)
    if request.method=="POST":
        json=request.json
        prod = Product()
        prod.name = json["name"]
        prod.description = json["description"]
        db.session.add(prod)
        db.session.commit()
        #insert product
        return product_schema.jsonify(prod)
예제 #12
0
def create_product():
    #pdb.set_trace()
    data = request.get_json()
    name = data.get('name')
    description = data.get('description')

    objProduct = Product()
    objProduct.name = name
    objProduct.description = description
    db.session.add(objProduct)
    db.session.commit()

    return ''
예제 #13
0
def create_product_with_thing_type(
        thing_name='Test Book',
        thing_type=ThingType.LIVRE_EDITION,
        author_name='Test Author',
        is_national=False,
        id_at_providers=None,
        date_modified_at_last_provider=None,
        last_provider_id=None,
        media_urls=['test/urls'],
        description=None,
        dominant_color=None,
        thumb_count=1,
        url=None,
        owning_offerer=None,
) -> Product:
    product = Product()
    product.type = str(thing_type)
    product.name = thing_name
    product.description = description
    product.extraData = {'author': author_name}
    product.isNational = is_national
    if id_at_providers is None:
        id_at_providers = ''.join(random.choices(string.digits, k=13))
    product.dateModifiedAtLastProvider = date_modified_at_last_provider
    product.lastProviderId = last_provider_id
    product.idAtProviders = id_at_providers
    product.mediaUrls = media_urls
    product.thumbCount = thumb_count
    product.url = url
    product.owningOfferer = owning_offerer

    if thumb_count > 0:
        if dominant_color is None:
            product.firstThumbDominantColor = b'\x00\x00\x00'
        else:
            product.firstThumbDominantColor = dominant_color
    product.description = description
    return product
예제 #14
0
def products():
    if request.method == 'GET':
        products = db.session.query(Product).all() # SQLAlchemy request => 'SELECT * FROM products'
        return products_schema.jsonify(products), 200

    if request.method == 'POST':
        if 'name' in request.get_json():
            product = Product()
            product.name = request.get_json()['name']
            if 'description' in request.get_json():
                product.description = request.get_json()['description']
            db.session.add(product)
            db.session.commit()
            return "Product created", 201
        return "Invalid product name", 400
예제 #15
0
def menuItems(item_id=None):
    # Get All Menu Items
    specific_vendor_id = get_jwt_identity()
    if request.method == 'GET':
        if item_id is None:
            vendor_items = Product.query.filter_by(
                vendor_id=specific_vendor_id).all()
            serialized_items = []
            for item in vendor_items:
                serialized_items.append(item.serialize())
            return jsonify(serialized_items), 200
        else:
            specific_item = Product.query.filter_by(id=item_id).one_or_none()
            return jsonify(specific_item.serialize()), 200
    elif request.method == 'POST':
        body = request.get_json()
        item = Product(name=body['name'],
                       category=body['category'],
                       vendor_id=specific_vendor_id,
                       price=body['price'],
                       description=body['description'])
        db.session.add(item)
        db.session.commit()
        print(item)
        return jsonify(item.serialize()), 201
    elif request.method == 'PUT':
        body = request.get_json()
        item = Product.query.get(item_id)
        if item is None:
            raise APIException('Menu item not found', status_code=404)
        if 'name' in body:
            item.name = body['name']
        if 'price' in body:
            item.price = body['price']
        if 'description' in body:
            item.description = body['description']
        if 'category' in body:
            item.category = body['category']
        db.session.commit()
        return jsonify(item.serialize()), 200

    elif request.method == 'DELETE':
        item = Product.query.get(item_id)
        if item is None:
            raise APIException('Item not found', status_code=404)
        db.session.delete(item)
        db.session.commit()
        return jsonify({}), 204
예제 #16
0
def create_product():
    content = request.json
    #Format des datas...
    if content is None:
        return jsonify({'ERROR': 'input data error'}), 422
    if "name" not in content:
        return jsonify({'ERROR': 'input data error'}), 422
    if content["name"] == "":
        return jsonify({'ERROR': 'input data error'}), 422

    product = Product()
    product.name = content["name"]
    product.description = content.get("description")
    db.session.add(product)
    db.session.commit()
    return jsonify({'id': product.id}), 201
예제 #17
0
파일: wsgi.py 프로젝트: lariau/sqlalchemy
def products():
    if request.method == 'GET':
        products = db.session.query(
            Product).all()  # SQLAlchemy request => 'SELECT * FROM products'
        return products_schema.jsonify(products)
    elif request.method == 'POST':
        content = request.get_json()
        new_product = Product()
        new_product.name = content['name']
        new_product.description = content['description']
        db.session.add(new_product)
        db.session.commit()
        return Response(
            f"added {content['name']} with desription {content['description']}",
            status=201,
            mimetype='application/json')
예제 #18
0
def fetch_category(search_index, amazon_node_id):
    api = caching.ResponseCachingAPI(
        settings.AMAZON_AWS_KEY,
        settings.AMAZON_SECRET_KEY,
        settings.AMAZON_API_LOCALE,
        settings.AMAZON_ASSOCIATE_TAG,
        cachedir='cache',
        cachetime=86400)

    try:
        for root in api.item_search(search_index, BrowseNode=str(amazon_node_id),
            ResponseGroup=settings.AMAZON_RESPONSE_GROUP):

            for item in root.Items.Item:
                product = Product()
                product.category = Category.objects.get(amazon_node_id=amazon_node_id)
                product.asin = item.ASIN
                product.title = unicode(item.ItemAttributes.Title)
                product.detailpageurl = unicode(item.DetailPageURL)
                product.manufacturer = unicode(getattr(item.ItemAttributes, 'Manufacturer', None))
                product.publisher = unicode(getattr(item.ItemAttributes, 'Publisher', None))
                product.brand = unicode(getattr(item.ItemAttributes, 'Brand', None))
                product.popularity = getattr(item, 'SalesRank', 1000)
                if hasattr(item, 'MediumImage'):
                    product.medium_image = getattr(item.MediumImage, 'URL', None)
                if hasattr(item, 'LargeImage'):
                    product.large_image = getattr(item.LargeImage, 'URL', None)
                if hasattr(item, 'EditorialReviews'):
                    product.description = unicode(getattr(item.EditorialReviews.EditorialReview, 'Content', None))
                if hasattr(item.Offers, 'Offer'):
                    product.price = item.Offers.Offer.OfferListing.Price.FormattedPrice.pyval
                elif hasattr(item.ItemAttributes, 'ListPrice'):
                    product.price = item.ItemAttributes.ListPrice.FormattedPrice.pyval
                elif hasattr(item.OfferSummary, 'LowestUsedPrice'):
                    product.price =  u'used from %s' % item.OfferSummary.LowestUsedPrice.FormattedPrice.pyval
                else:
                    product.price = None
                product.save()

    except AWSError, e:
        if e.code == 'AWS.ParameterOutOfRange':
            pass # reached the api limit of 10 pages
        else:
            raise ValidationError(message=e.msg)
예제 #19
0
def post_product():
    _name_product = request.json.get('name_product')
    _description = request.json.get('description')
    _price = request.json.get('price')
    id_restaurant = request.json.get("id_restaurant")
    if not _name_product or _name_product == '':
        return jsonify({'msg': 'Field name product is required'}), 400
    if not _price or _price == '':
        return jsonify({'msg': 'Field price is required'}), 400
    if not id_restaurant or id_restaurant == '':
        return jsonify({'msg': 'Field restaurant_id is required'}), 400
    _product = Product()
    _product.name_product = _name_product
    _product.description = _description
    _product.id_restaurant = id_restaurant
    _product.price = _price
    db.session.add(_product)
    db.session.commit()
    return jsonify({"msg": "producto registrado"}), 200
예제 #20
0
def create_product():
    product = Product()
    body = request.get_json()

    # Test en version condensee
    # filtered_body = { key, value for key, value in body if key in ["name","description"]}
    #product = Product(**filtered_body)

    name = body.get("name")  # Test dans le body que name existe
    if name is not None:
        product.name = name

    description = body.get(
        "description")  # Test dans le body que la description existe
    if description is not None:
        product.description = description

    db.session.add(product)
    db.session.commit()
    return product_schema.jsonify(product), 201
def products_to_db(products):
    """
    It saves the products in the database
    :param products: dictionary with the desired information
    """
    session = load_session()
    for key, item in products.items():
        print('\n>>> Processing:', key, item['NAME'])
        product = (session.query(Product).filter_by(store="Richart's",
                                                    sku=item["SKU"]).first())

        if product is None:
            product = Product(store="Richart's", sku=item["SKU"])

        product.barcodes = item["BARCODES"]
        product.brand = item["BRAND"].capitalize()
        product.name = item["NAME"].capitalize()
        description = remove_html_tags(item["DESCRIPTION"])
        product.description = description.capitalize()
        product.image_url = item["IMAGE_URL"]
        product.category = item["FULL_CATEGORY"]
        product.package = product.description.replace(product.name, '')

        session.add(product)
        session.commit()

        # Check if the BranchProduct already exists
        branch_product = (session.query(BranchProduct).filter_by(
            product=product, branch=item["BRANCH"]).first())

        if branch_product is None:
            branch_product = BranchProduct(product=product,
                                           branch=item["BRANCH"])

        branch_product.stock = item["STOCK"]
        branch_product.price = item["PRICE"]

        session.add(branch_product)
        session.commit()

    session.close()
예제 #22
0
def process_item(item):

    Session = sessionmaker(bind=engine)
    session = Session()
    # Check if the Product already exists
    product = (session.query(Product).filter_by(store=item["store"],
                                                sku=item["sku"]).first())

    if product is None:
        product = Product(store=item["store"], sku=item["sku"])

    product.barcodes = item["barcodes"]
    product.brand = item["brand"]
    product.name = item["name"]
    product.description = item["description"]
    product.image_url = item["image_url"]
    product.category = item["category"]
    product.package = item["package"]

    session.add(product)
    session.commit()

    # Check if the BranchProduct already exists
    branch_product = (session.query(BranchProduct).filter_by(
        product=product, branch=item["branch"]).first())

    if branch_product is None:
        branch_product = BranchProduct(product=product, branch=item["branch"])

    branch_product.stock = item["stock"]
    branch_product.price = item["price"]

    session.add(branch_product)
    session.commit()

    return item
예제 #23
0
    def saveProduct(self, product):
        try:
            record = Product()
            if Product.objects.filter(title=str(product['title'])).exists():
                record = Product.objects.filter(title=str(product['title']))[0]
            record.title = str(product['title'])
            record.description = str(product['description'])
            record.current_price = formatPrice(
                product['price']['current_price'] if 'current_price' in
                product['price'] else 0)
            record.old_price = formatPrice(
                product['price']['old_price'] if 'old_price' in
                product['price'] else 0)
            record.you_save = formatPrice(
                product['price']['you_save'] if 'you_save' in
                product['price'] else 0)
            record.url = str(product['url'])
            record.images = product['images']
            if product['connections']:
                record.connection_value = str(product['connections'])

            record.manufacturer_en = str(product['manufacturer_en'])
            record.brand = str(product['manufacturer_en']
                               ) if product['manufacturer_en'] else str(
                                   product['seller']['name'])
            record.tags = product['tags']
            record.other_specs = str(product['specs'])
            record.original_json = json.dumps(product, ensure_ascii=False)

            record.save()
            return record
        except Exception as e:

            print('Error during save proudct {}  cause {} '.format(
                product['title'], str(e)))
            return None
예제 #24
0
def Addproduct(request):
    form = ProductForm(request.POST or None)
    if form.is_valid():
        ModelName = form.cleaned_data['ModelName']
        description = form.cleaned_data['description']
        photo = form.cleaned_data['photo']
        manufacturer = form.cleaned_data['manufacturer']
        price_in_dollars = form.cleaned_data['price_in_dollars']
        Quantity = form.cleaned_data['Quantity']
        Serial_No = form.cleaned_data['Serial_No']
        product = Product()
        product.ModelName = ModelName
        product.description = description
        product.photo = photo
        product.manufacturer = manufacturer
        product.price_in_dollars = price_in_dollars
        product.Quantity = Quantity
        product.Serial_No = Serial_No
        product.save()
        return HttpResponseRedirect(reverse('ecom:product'))

        #return HttpResponseRedirect(reverse('ecom:product'))
    else:
        return render(request, "ItemMaster.html", {"form": form})
예제 #25
0
def products(id=None, category_id=None):
    if request.method == 'GET':
        if id is not None and category_id is not None:
            product = Product.query.filter_by(category_id=category_id,
                                              id=id).first()
            if product:
                return jsonify(product.serialize()), 200
            else:
                return jsonify({"product": "Not found"}), 404
        elif id is not None:
            product = Product.query.get(id)
            if product:
                return jsonify(product.serialize()), 200
            else:
                return jsonify({"product": "Not found"})
        elif category_id is not None:
            products = Product.query.filter_by(category_id=category_id).all()
            products = list(map(lambda product: product.serialize(), products))
            return jsonify(products), 200
        else:
            products = Product.query.all()
            products = list(map(lambda product: product.serialize(), products))
            return jsonify(products), 200

    if request.method == 'POST':
        thing_name = request.json.get('thing_name')
        price = request.json.get('price')
        description = request.json.get('description')
        not_available = request.json.get('not_available')
        category_id = request.json.get('category_id')
        quantity = request.json.get('quantity')
        if not thing_name:
            return jsonify({"msg": "Name is required"}), 422
        if not quantity:
            return jsonify({"msg": "Quantity is required"}), 422
        if not price:
            return jsonify({"msg": "price is required"}), 422
        if not description:
            return jsonify({"msg": "description is required"}), 422
        if not not_available:
            return jsonify({"msg": "product is not available"}), 422
        if not category_id:
            return jsonify({"msg": "category_id is not available"}), 422

        product = Product()
        product.thing_name = thing_name
        product.price = price
        product.quantity = quantity
        product.description = description
        product.not_available = not_available
        product.category_id = category_id
        db.session.add(product)
        db.session.commit()
        return jsonify(product.serialize()), 201

    if request.method == 'PUT':

        product = Product.query.get(id)
        product.thing_name = request.json.get('thing_name')
        product.price = request.json.get('price')
        product.description = request.json.get('description')
        product.not_available = request.json.get('not_available')
        product.quantity = request.json.get('quantity')
        db.session.commit()
        return jsonify(product.serialize()), 200
    if request.method == 'DELETE':

        product = Product.query.get(id)
        db.session.delete(product)
        db.session.commit()
        return jsonify({'product': 'Deleted'}), 200