def post(self):
		book_type = self.request.get('type')
		if book_type is None:
			logging.info('None')
			self.redirect('/bookdetails')
		else:
			logging.info('Book type: %s', book_type)

		type_name = Type.query(Type.name == book_type).get()
		if type_name is None:
			logging.info('None')
			self.redirect('/bookdetails')
		else:
			logging.info('Type %s',book_type)

		book_details = Product()

		if self.request.get('img'):
			book_details.image = db.Blob (images.resize(self.request.get('img'), 350, 450))

		book_details.bookId = self.request.get('bookcode')
		book_details.title = self.request.get('title')
		book_details.category = type_name.key
		book_details.author = self.request.get('author')
		book_details.price = self.request.get('price')
		book_details.descrip = self.request.get('editor1')
		book_details.put()

		logging.info('Added book with: %s', book_details.bookId)
		self.redirect('/bookdetails')
Esempio n. 2
0
def createProduct():
    sess = DBSession()
    current_user = get_jwt_identity()
    user = sess.query(User).filter_by(id=current_user).first()
    #manager = sess.query(User).filter_by(id=current_user,isManager=True).first()
    if not user.isManager:
        return jsonify({"msg": "No Permission"}), 401

    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400

    title = request.json.get('title')
    if not title:
        return jsonify({"msg": "Missing title parameter"}), 400
    
    category = request.json.get('category')
    if not category:
        return jsonify({"msg": "Missing category parameter"}), 400

    storehouse_id = request.json.get('storehouse_id')
    if not storehouse_id:
        return jsonify({"msg": "Missing storehouse_id parameter"}), 400
    
    dictdata = request.json.get('dictdata')
    if not dictdata:
        return jsonify({"msg": "Missing dictdata parameter"}), 400

    product = Product(title,category,storehouse_id)
    product.update(dictdata)
    sess.add(product)
    sess.commit()
    return jsonify(result=True, productId=product.id)
Esempio n. 3
0
    def post(self):
        thefile = self.request.params['prductImage']
        newImageFile = DbFile(name=thefile.filename,
                              data=db.Blob(thefile.value),
                              type=thefile.type)
        newImageFile.put()
        theDetailFile = self.request.params['prductDetailImage']
        newImageDetailFile = DbFile(name=theDetailFile.filename,
                                    data=db.Blob(theDetailFile.value),
                                    type=theDetailFile.type)
        newImageDetailFile.put()
        newName = self.request.params['productName']
        newDescription = self.request.params['productDescription']
        newPrice = float(self.request.params['productPrice'])
        newImagePath = '/Files/' + newImageFile.name
        newImageDetailPath = '/Files/' + newImageDetailFile.name

        product = Product(name=newName,
                          description=newDescription,
                          price=newPrice,
                          imagePath=newImagePath,
                          imageFile=newImageFile,
                          imageDetailPath=newImageDetailPath,
                          imageDetailFile=newImageDetailFile)
        product.put()
        self.postRedirect()
 def setUp(self) -> None:
     super().setUp()
     self.warehouse = Warehouse(":memory:", create_tables=True)
     self.warehouse.create_product(Product("W1", "Вино", "Бутылка"))
     self.warehouse.create_product(Product("P1", "Пармезан", "Килограмм"))
     self.warehouse.create_product(Product("C1", "Колбаса", "Килограмм"))
     customer = self.warehouse.create_customer("Виталий Брагилевский")
     self.cid = customer.id
Esempio n. 5
0
def get_all_products(only_monitoring=True):
    if only_monitoring:  # only update those are monitored
        monitoring = Monitor.query(Monitor.switch == True).fetch()
        product_ids = {_.target for _ in monitoring}
        products = [Product.get_by_id(key) for key in product_ids]
    else:
        products = Product.query().fetch()
    return products
Esempio n. 6
0
 async def fetch_async(url):
     async with aiohttp.ClientSession() as session:
         async with session.get(url) as resp:
             print(resp.status)
             data = await resp.text()
             p = Product()
             p.parse(data)
             print(p.__dict__)
             return p
Esempio n. 7
0
def buy_intent(product_name):
    products = Product(context.System.apiAccessToken)
    logger.info("PRODUCT: {}".format(product_name))
    buy_card = render_template('buy_card', product=product_name)
    productId = products.productId(product_name)
    if productId is not None:
        session.attributes[PRODUCT_KEY] = productId
    else:
        return statement("I didn't find a product {}".format(product_name))
        raise NotImplementedError()
    return buy(productId).simple_card('Welcome', question_text)
Esempio n. 8
0
def refund_intent(product_name):
    refund_card = render_template('refund_card')
    logger.info("PRODUCT: {}".format(product_name))

    products = Product(context.System.apiAccessToken)
    productId = products.productId(product_name)

    if productId is not None:
        session.attributes[PRODUCT_KEY] = productId
    else:
        raise NotImplementedError()
    return refund(productId)
Esempio n. 9
0
def add_entry():

    if not session.get('logged_in'):
        abort(401)

    url = request.form['url']

    # Add product to DB
    existing = Product.query.filter(Product.url == url).first()
    e = None
    product = None
    if not existing:
        #Query Amazon
        try:
            product = azcrawler.crawl_url(url)
            if product is None:
                flash("Amazon doesn't sell this product today!")
                return redirect(url_for('show_entries'))
            e  = Product(product[0], url , product[2], float(product[1][0]))
            e.prev_price = 0
            db = get_db()
            db.session.add(e)
            db.session.commit()
        except:
            flash("Error fetching product...")
            return redirect(url_for('show_entries'))

    existing =  existing or e
    # Add Subscription
    s = Subscription.query.filter(Subscription.user_id == session['userid'],
                                 Subscription.prod_id == existing.id).first()
    if not s:
      try:
          print "Adding subscription"
          sub = Subscription(existing.id, session['userid'])
          db = get_db()
          db.session.add(sub)
          updt = DinoUpdate(json.dumps(
                                {"title": existing.title, 
                                "message": "Watching currently at $%s"%(existing.curr_price),
                                "url": existing.url,
                                "img": existing.img_url,
                                "merchant": utils.get_merchant_name(existing.url),
                                "mag" : 0, 
                                "userid": session['userid']}),
                                session['userid'], 
                                existing.id)
          print "Adding subscription %s"% updt
          db.session.add(updt)
          db.session.commit()
      except Exception, e:
          print "DB Tx failed: %s"%str(e)
Esempio n. 10
0
def create_product_entity(link, currency, current, history, meta):
    product = Product.get_by_id(id=meta["asin"])
    if product is not None:
        return product.key
    else:
        product = Product(id=meta["asin"],
                          link=link,
                          currency=currency,
                          current=current,
                          history=history,
                          meta=meta)
        key = product.put()
        return key
Esempio n. 11
0
def completed(payload, name, status, token):
    products = Product(context.System.apiAccessToken)
    logger.info('on-purchase-completed {}'.format( request))
    logger.info('payload: {} {}'.format(payload.purchaseResult, payload.productId))
    logger.info('name: {}'.format(name))
    logger.info('token: {}'.format(token))
    logger.info('status: {}'.format( status.code == 200))
    product_name = products.productName(payload.productId)
    logger.info('Product name'.format(product_name))
    if status.code == '200' and ('ACCEPTED' in payload.purchaseResult):
        return question('To listen it just say - play {} '.format(product_name))
    else:      
        return question('Do you want to buy another product?')
Esempio n. 12
0
def save_product(session, product_dict, shop):
    print("save_product")
    if product_dict['price'] == 0:
        return
    product = session.query(Product).filter_by(
        external_id=product_dict['external_id'], shop_id=shop.id
    ).first()
    if not product:
        product = Product(
            title=product_dict['title'], description=product_dict['description'], url=product_dict['url'],
            current_price=product_dict['price'], lowest_price=product_dict['price'], lowest_price_aberrance=1.0,
            external_id=product_dict['external_id']
        )
        shop.products.append(product)
        session.add(product)
        logging.info("added product with url: {}, title: {}".format(product.url, product.title))
        print("added product with url: {}, title: {}".format(product.url, product.title))
    else:
        logging.info("shop {}, product id {} existiert schon als name {} und url {}\n".format(
            shop.name, product_dict['external_id'], product.title, product.url
        ))
        print("shop {}, product id {} existiert schon als name {} und url {}\n".format(
            shop.name, product_dict['external_id'], product.title, product.url
        ))
        product.title = product_dict['title']
        product.description = product_dict['description']
        product.url = product_dict['url']
        product.current_price = product_dict['price']
        product.lowest_price = min(product_dict['price'], product.lowest_price)
        product.lowest_price_aberrance = product.current_price / product.lowest_price

    product.prices.append(Price(value=product_dict['price'], date=datetime.date.today()))
Esempio n. 13
0
class ProductPersistence:
    products = [
        Product(1111111, 'FIBRA 1000 ADAMO', 'ftth', 933933933, '2019-01-09 14:26:17', 555555, brands.nintendo),
        Product(1111112, 'Toy Story 5', 'Bluray Disc', 922922922, '2020-11-24 09:23:17', 555556, brands.pixar),
        Product(1111113, 'FIBRA 1000 ADAMO', 'ftth', 933933933, '2020-11-24 09:23:18', 555556, brands.nintendo)
    ]

    def get_all_products(self):
        return self.products

    def get_product_by_id(self, id):
        for product in self.products:
            if product._id == id:
                return product
Esempio n. 14
0
def get_product(save_db=False):
    query = """
    SELECT id, name, url FROM categories
    WHERE parent_id BETWEEN 100 AND 113;
    """
    try:
        cur.execute(query)
    except Exception as err:
        print('ERROR BY SELECT TABLE', err)

    rows = cur.fetchall()
    
    for i in rows:
        id = i[0]
        name = " ".join(i[1].strip().split()[:-1])
        url = i[2].strip()
        for page in range(1,4):
            page_url = url + "&page=" + str(page)
#             print(page_url)
            page_html = get_url(page_url)
            try:
                products_wrapper_div = page_html.find_all('div', class_='product-box-list')[0]
            except Exception as err:
                 print('ERROR BY DIV FINDALL: ', err)
            if products_wrapper_div:
                products_div = products_wrapper_div.find_all('div', class_='product-item')
                result = []
                if len(products_div) > 0:
                    for product_div in products_div:
                        product_id = None
                        title = product_div.a['title']
                        url = product_div.a['href']
                        img_url = product_div.img['src']
                        regular_price = product_div.find('span', class_='price-regular').text
                        final_price = product_div.find('span', class_='final-price').text.split()[0]
                        sale_tag = product_div.find('span', class_='sale-tag').text
                        comment = product_div.find('p', class_='review').text.split()[0] + ' review(s))'
                        if product_div.find('span', class_='rating-content'):
                            rating = product_div.find('span', class_='rating-content').find('span')['style'].split(":")[-1]
                        else:
                            rating = '0%'
                        product = Product(product_id, name, url, img_url, regular_price, final_price, sale_tag, comment, rating, id)

                        if save_db:
                            product.save_into_db()
                            print(f'SAVE {title} INTO DB')
                        result.append(product)
                else:
                    break
Esempio n. 15
0
def completed(payload, name, status, token):
    products = Product(context.System.apiAccessToken)
    logger.info("on-purchase-completed {}".format(request))
    logger.info("payload: {} {}".format(payload.purchaseResult,
                                        payload.productId))
    logger.info("name: {}".format(name))
    logger.info("token: {}".format(token))
    logger.info("status: {}".format(status.code == 200))
    product_name = products.productName(payload.productId)
    logger.info("Product name".format(product_name))
    if status.code == "200" and ("ACCEPTED" in payload.purchaseResult):
        return question(
            "To listen it just say - play {} ".format(product_name))
    else:
        return question("Do you want to buy another product?")
    def test_can_get_list_of_products(self):
        """Test that we can get an example repository of product from file.
        """

        gift_repo = Product.get_example_gift_repository(self.db_conn)

        self.assertEqual(len(gift_repo), 20)
Esempio n. 17
0
def add_product_to_table(row_list, attr_list):
    """Add one row of product CSV file to five talbes.

    products, category_detail_values,
    product_details, category_attributes, category_details."""

    cg = Category.query.filter_by(cg_name=row_list[1].lower()).first()

    product = Product(
        user_id=1,  # session["user_id"],
        prd_name=row_list[0],
        cg_id=cg.cg_id,
        sale_price=row_list[2],
        description=row_list[3])

    try:
        db.session.add(product)
        db.session.commit()
    except IntegrityError:
        db.session.rollback()
        return "fail"

    attr_val = row_list[4:]
    val_list = []

    # read values of attributes.
    for i, val in enumerate(attr_val):

        attr = CategoryAttribute.query.filter_by(
            attr_name=attr_list[i]).first()

        val = val.lower()

        # adding attribute-value pairs into category_attributes.
        is_attr = CategoryDetailValue.query.filter_by(
            cg_attr_id=attr.cg_attr_id, attr_val=val).first()
        if is_attr and val != '':
            val_list.append(is_attr)

        elif is_attr and val == '':
            continue

        elif not is_attr and val != '':
            new_val = CategoryDetailValue(cg_attr_id=attr.cg_attr_id,
                                          attr_val=val)
            db.session.add(new_val)
            val_list.append(new_val)

        # adding category-attribute pairs into category_attributes.
        if CategoryDetail.query.filter_by(
                cg_id=cg.cg_id,
                cg_attr_id=attr.cg_attr_id).first() or val == '':
            continue
        else:
            cg.cgattribute.append(attr)

    product.prddetail.extend(val_list)
    db.session.commit()

    return "Submit successfully!"
Esempio n. 18
0
 def test(self):
     noodles = self.table.create_product(Product(sku="F-234", name="Макароны", units="Упаковка"))
     product = self.table.find_product("F-234")
     self.assertEqual(noodles, product)
     self.table.delete_product("F-234")
     product = self.table.find_product("F-234")
     self.assertEqual(None, product)
Esempio n. 19
0
  def GarbageCollectBlobs(self):
    keys_to_blobs = {}
    for blob in BlobInfo.all():
      keys_to_blobs[blob.key()] = blob

    for responder in Responder.all():
      image_blob = responder.image_data
      if image_blob:
        key = image_blob.key()
        if key in keys_to_blobs:
          del keys_to_blobs[key]

    for product in Product.all():
      image_blob = product.image_data
      if image_blob:
        key = image_blob.key()
        if key in keys_to_blobs:
          del keys_to_blobs[key]

    for key, blob_info in keys_to_blobs.iteritems():
      logging.info('deleting %s' % key)
      blob_info.delete()

    if keys_to_blobs:
      return 'Deleted blobs: \n%s' % '\n'.join(str(k) for k in keys_to_blobs)
    else:
      return 'No blobs to delete'
Esempio n. 20
0
def profile_products():
    if request.method == 'POST':
        dao.add_product(
            user,
            Product(request.form.get('name'), request.form.get('quantity'),
                    request.form.get('unit')))
    return render_template('products.html', profile=user)
Esempio n. 21
0
    def get(self, cid):
        page = int(
            self.get_argument("page", '1')
            if len(self.get_argument("page", '1')) > 0 else '1')
        pagesize = self.settings['admin_pagesize']

        category = Category_Store.get(id=cid)

        ft = ((Product.status > 0) & (Product.category_store == category))
        q = Product.select().where(ft)
        total = q.count()

        if total % pagesize > 0:
            totalpage = total / pagesize + 1
        else:
            totalpage = total / pagesize
        products = q.paginate(page, pagesize)

        self.render('/store/category/category_product.html',
                    products=products,
                    total=total,
                    page=page,
                    pagesize=pagesize,
                    totalpage=totalpage,
                    category=category,
                    active='categorys')
Esempio n. 22
0
    def get(self, pid, status):
        page = int(
            self.get_argument("page", '1')
            if len(self.get_argument("page", '1')) > 0 else '1')
        cid = int(self.get_argument("cid", 0))
        keyword = self.get_argument("keyword", None)
        ds = self.get_argument("ds", None)
        s = int(self.get_argument("status", 1))

        p = Product.get(Product.id == pid)
        content = {}
        content['operatetype'] = '修改产品状态'
        content['pid'] = pid
        content['old_status'] = p.status
        content['current_status'] = status
        p.status = status
        p.updatedtime = int(time.time())
        p.updatedby = self.get_store_user()
        p.save()
        AdminLog.create(user=self.get_store_user(),
                        dotime=int(time.time()),
                        content=content)
        self.redirect('/store/products?page=' + str(page) + '&pcategory=' +
                      str(cid) + '&keyword=' + keyword + '&defaultstandard=' +
                      str(ds) + '&status=' + str(s))
Esempio n. 23
0
    def test_product_type(self):
        image_url = """https://images.asos-media.com/products/"""
        """vestido-largo-y-plisado-de-dama-de-honor-en-rosa-exclusivo-de-tfnc/"""
        """13955198-2?$XXL$&wid=513&fit=constrain"""
        product_url = """https://www.asos.com/es/tfnc/"""
        """vestido-largo-y-plisado-de-dama-de-honor-en-rosa-exclusivo-de-tfnc/"""
        """prd/13955198?clr=rosa&colourWayId=16579390&SearchQuery=&cid=17245"""
        description = "Vestido largo y plisado de dama de honor en rosa exclusivo de TFNC"
        images = [Image(url=image_url) for x in range(5)]  # 5 fake images
        product = Product(uid="sku1000",
                          images=images,
                          gender="female",
                          product_url=product_url,
                          price=82.99,
                          category="dress",
                          size="M",
                          description=description)

        self.assertTrue(hasattr(product, "uid"))
        self.assertTrue(hasattr(product, "images"))
        self.assertTrue(hasattr(product, "gender"))
        self.assertTrue(hasattr(product, "product_url"))
        self.assertTrue(hasattr(product, "price"))
        self.assertTrue(hasattr(product, "size"))
        self.assertTrue(hasattr(product, "category"))
        self.assertTrue(hasattr(product, "description"))

        self.assertIsInstance(product.images, list)
        self.assertIsInstance(product.gender, str)
        self.assertIsInstance(product.product_url, str)
        self.assertIsInstance(product.price, float)
        self.assertIsInstance(product.size, str)
        self.assertIsInstance(product.category, str)
        self.assertIsInstance(product.description, str)
Esempio n. 24
0
def add_product(id,name,price,description,picture_link):
	    product_object = Product(
	    Id=Id,
        name=name,
        price=price,
        description=description,
        picture_link=picture_link)
Esempio n. 25
0
def add_product(name, price, picture_link, description):
    product_object = Product(name=name,
                             price=price,
                             picture_link=picture_link,
                             description=description)
    session.add(product_object)
    session.commit()
	def get(self):
		if users.get_current_user():
			url = users.create_logout_url(self.request.uri)
			url_linktext = 'Click here to log out'
			if users.is_current_user_admin():
				self.redirect('/booktype')
		else:
			url = users.create_login_url(self.request.uri)
			url_linktext = 'Click here to log in'

		all_book_types = Type.query().order(Type.code).fetch()
		all_book_details = Product.query().order(Product.bookId).fetch()

		type_code = self.request.get('code')
		if type_code is None:
			logging.info('No code supplied')
			self.redirect('/')
		else:
			logging.info('Book type code %s', type_code)

		book_type = Type.query(Type.code == type_code).get()
		if book_type is None:
			logging.info('Cannot find type with code %s', type_code)
			self.redirect('/')

		template_values = {
			'all_book_types': all_book_types, 
			'book_type': book_type,
			'all_book_details': all_book_details,
			'url': url,
			'url_linktext': url_linktext,
		}
		template = JINJA_ENVIRONMENT.get_template('/product.html')
		self.response.write(template.render(template_values))
Esempio n. 27
0
def add_product(name, price, link, description):
    new_prod = Product(name=name,
                       price=price,
                       link=link,
                       description=description)
    session.add(student_object)
    sessin.commit()
Esempio n. 28
0
def add_product(name, Price, Picturelink, Descroption):
    product_object = Product(name=name,
                             Price=Price,
                             Picturelink=Picturelink,
                             Description=Descroption)
    session.add(product_object)
    session.commit()
def add_product(Name, Price, Picture_Link, Description):
    producta = Product(Name=name,
                       Price=Price,
                       Picture_Link=Picture_Link,
                       Description=Description)
    session.add(producta)
    session.commit()
Esempio n. 30
0
def add_product(name, price, picture_link, desc):
    Product_object = Product(name=name,
                             price=price,
                             picture_link=picture_link,
                             desc=desc)
    session.add(Product_object)
    session.commit()
Esempio n. 31
0
def add_product(name, price, maker, picture):
    product_object = Product(name=name,
                             price=price,
                             maker=maker,
                             picture=picture)
    session.add(user_object)
    session.commit()
Esempio n. 32
0
def add_product(name, price, picture_link, description):
    Camera_01 = Product(name=name,
                        price=price,
                        picture_link=picture_link,
                        description=description)
    session.add(Camera_01)
    session.commit()
Esempio n. 33
0
def addProduct(product_name, product_price, picture_link, product_description):
    new_product = Product(name=product_name,
                          price=product_price,
                          picture_link=picture_link,
                          description=product_description)
    session.add(new_product)
    session.commit()
Esempio n. 34
0
    def GarbageCollectBlobs(self):
        keys_to_blobs = {}
        for blob in BlobInfo.all():
            keys_to_blobs[blob.key()] = blob

        for responder in Responder.all():
            image_blob = responder.image_data
            if image_blob:
                key = image_blob.key()
                if key in keys_to_blobs:
                    del keys_to_blobs[key]

        for product in Product.all():
            image_blob = product.image_data
            if image_blob:
                key = image_blob.key()
                if key in keys_to_blobs:
                    del keys_to_blobs[key]

        for key, blob_info in keys_to_blobs.iteritems():
            logging.info('deleting %s' % key)
            blob_info.delete()

        if keys_to_blobs:
            return 'Deleted blobs: \n%s' % '\n'.join(
                str(k) for k in keys_to_blobs)
        else:
            return 'No blobs to delete'
	def get(self):
		img_key = ndb.Key('Product', int(self.request.get('img_id')))
		book_details = Product.query(Product.key == img_key).get()
		if book_details.image:
			self.response.headers['Content_Type'] = 'image/png'
			self.response.out.write(book_details.image)
		else:
			self.response.out.write('No image')
Esempio n. 36
0
 def ProductCount(self):
   """Return the number of product."""
   product_count = memcache.get(memcache_keys.PRODUCT_COUNT_KEY)
   if product_count is None:
     product_count = Responder.all().count() + Product.all().count()
     if not memcache.add(memcache_keys.PRODUCT_COUNT_KEY, product_count):
       logging.error("Memcache set failed.")
   return product_count
Esempio n. 37
0
 def create_product(name, barcode, category):
     """ Create a product in datastore """
     query = Product.all()
     query.filter("barcode =", barcode)
     ret = query.get()
     if ret is None:
         ret = Product()
         ret.barcode = barcode
         ret.set_name(name)
         ret.category = category
         ret.put()
         AdminWorkerHandler.update_search_table(ret)
     return ret
Esempio n. 38
0
  def get(self):
    key = self.request.get('key')
    product = Product.get(key)
    if not product:
      return

    if product.image_url and not product.image_data:
      fetcher = ImageFetcher()
      blob_key = fetcher.FetchAndSaveImage(product.image_url)

      if blob_key:
        product.image_data = blob_key
        product.image_serving_url = images.get_serving_url(blob_key)
        product.put()
    return
Esempio n. 39
0
    def get(self, api=None, product_id=None):
        """ GET request handler """
        self.response.headers['Content-Type'] = 'application/json'
        # TODO !!!!!! REMOVE ON RELEASE !!!!!!!!!!
        self.response.headers['Access-Control-Allow-Origin'] = '*'
        # TODO !!!!!! REMOVE ON RELEASE !!!!!!!!!!

        if api is None:
            return

        if product_id is None:
            query = self.request.get('q', '')
            product_list = Product.search(query)
            self.response.out.write(product_list)
        else:
            pass
	def delete(self):
		logging.info('In delete')

		book_code = self.request.get('code')
		if book_code is None:
			logging.info('No code supplied')
			self.redirect('/bookdetails')
		else:
			logging.info('Book code %s', book_code)

		book_details = Product.query(Product.bookId == book_code).get()
		if book_details is None:
			logging.info('Cannot find book with code %s', book_code)
			self.redirect('/bookdetails')

		book_details.key.delete()
		self.redirect('/bookdetails')
	def get(self):
		if users.get_current_user():
			url = users.create_logout_url(self.request.uri)
			url_linktext = 'LOG OUT'

			if users.is_current_user_admin():
				template = JINJA_ENVIRONMENT.get_template('/bookdetails.html')
				all_book_details = Product.query().order(Product.bookId).fetch()
				template_values = {
					'all_book_details': all_book_details,
					'url': url,
					'url_linktext': url_linktext,
				}
				self.response.write(template.render(template_values))
			else:
				self.redirect('/')
		else:
			self.redirect('/')
Esempio n. 42
0
  def InitiateImageFetch(self):
    """Add /fetch_image tasks for all responders missing image data."""
    urls = []
    for responder in Responder.all():
      if responder.image_url and not responder.image_data:
        url = '/tasks/fetch_image?key=%s' % responder.key()
        task = taskqueue.Task(method='GET', url=url)
        task.add()
        urls.append(responder.image_url)

    for product in Product.all():
      if product.image_url and not product.image_data:
        url = '/tasks/fetch_product_image?key=%s' % product.key()
        task = taskqueue.Task(method='GET', url=url)
        task.add()
        urls.append(product.image_url)

    if urls:
      return 'Fetching urls: \n%s' % '\n'.join(urls)
    else:
      return 'No images to fetch'
 def get_product(self,values,productid,product,price):
   if productid:
     result=Product.gql("where ean=:1 limit 1",productid).get()
     if not result:
       if price and product:
         result=Product()
         result.ean=productid
         result.name=product
         result.price=int(float(price)*100)
         result.put()
     else:
       product=result.name
       price=result.price
   else:
     result=None
   values["productid"]=productid
   values["product"]=product
   values["price"]=price
   return result
	def post(self):
		book_type = self.request.get('type')
		if book_type is None:
			logging.info('None')
			self.redirect('/bookdetails')
		else:
			logging.info('Book type:  %s', book_type)

		type_name = Type.query(Type.name == book_type).get()
		if type_name is None:
			logging.info('None')
			self.redirect('/bookdetails')
		else:
			logging.info('type %s',book_type)

		book_code = self.request.get('bookcode')
		if book_code is None:
			logging.info('No id supplied')
			self.redirect('/bookdetails')
		else:
			logging.info('Type id is %s', book_code)
		book_details = Product.query(Product.bookId == book_code).get()
		if book_details is None:
			logging.info('Cannot find type with code %s', book_code)

		picture = self.request.get('img')
		if picture:
			pic = images.resize(picture, 350, 450)
			book_details.image = db.Blob (pic)	
		
		book_details.bookId = self.request.get('bookcode')
		book_details.title = self.request.get('title')
		book_details.category = type_name.key
		book_details.author = self.request.get('author')
		book_details.price = self.request.get('price')
		book_details.descrip = self.request.get('editor1')
		book_details.put()

		logging.info('Edited book with id: %s', book_details.bookId)
		self.redirect('/bookdetails')
	def get(self):
		if users.get_current_user():
			url = users.create_logout_url(self.request.uri)
			url_linktext = 'LOG OUT'

			if users.is_current_user_admin():
				types = Type.query().fetch()
				if types is None:
					logging.info('None')
					self.redirect('/bookdetails')
				else:
					logging.info('Not none')

				book_code = self.request.get('code')
				if book_code is None:
					logging.info('No code supplied')
					self.redirect('/bookdetails')
				else:
					logging.info('Book code %s', book_code)

				book_details = Product.query(Product.bookId == book_code).get()
				if book_details is None:
					logging.info('Cannot find book with code %s', book_code)

				template_values = {
					'book_details': book_details, 
					'types': types,
					'url': url,
					'url_linktext': url_linktext,
				}
				template = JINJA_ENVIRONMENT.get_template('/bookdetails_edit.html')
				self.response.write(template.render(template_values))
			else:
				self.redirect('/')
		else:
			self.redirect('/')
Esempio n. 46
0
 def get(self, poffSet, pageRecNo):
     q = Product.query()
     products = q.fetch(offset=int(poffSet),limit=int(pageRecNo))
     r = [ AsDict(p) for p in products ]
     self.SendJson(r)
Esempio n. 47
0
def launch():
    products = Product(context.System.apiAccessToken)
    question_text = render_template('welcome', products=products.list())
    reprompt_text = render_template('welcome_reprompt')
    return question(question_text).reprompt(reprompt_text).simple_card('Welcome', question_text)
Esempio n. 48
0
 def post(self):
     myproduct = Product()
     myproduct.Product_Id = self.request.get('Product_Id')
     myproduct.Product_Name = self.request.get('Product_Name')
     myproduct.Catalog_Id = self.request.get('Catalog_Id')
     myproduct.put()