def do_work(self, urlsafeProductKey, qnt): try: ##: Get the Product Model and Best Price productModel, best_price = bestPrice.getBestPrice( urlsafeProductKey, int(qnt), returnProductModel=True) if best_price == None: logging.error('Error, Best Price not determined. ') raise Exception('Best Price not determined.') ndb.Key(urlsafe=urlsafeProductKey).get() if productModel == None: logging.error('Error, No Product Model Found ') raise Exception('No Product Model Found using urlsafe key') ##: Run a query for existing Carts the user has. (PUBLIC Carts) cartList = shoppingModels.Cart.get_carts_for_user(self.user_key) params = {'product': productModel, 'cartList': cartList, 'requested_quantity': int(qnt), 'best_price': utils.dollar_float(float(best_price)), 'total_cost': utils.dollar_float(float(best_price)*float(qnt)),} self.bournee_template('selectCartForm.html', **params) except Exception as e: logging.error('Error, function do_work of class AddToSelectedCartFormHandler: -- %s' % str(e)) message = _('We are having difficulties displaying the form at this time. Please check your entry and try again later.') self.add_message(message, 'error') try: self.redirect(self.request.referer) except: self.redirect_to('home')
def doWork(self, partKey): """ This is a common function for both Methods GET and POST """ productModel = None best_Price = None ##: Remeber the there is a Module called bestPrice... try: ##: Get the Product Model and Best Price ##: partKey is a urlSafe key from the request URL best_Price = bestPrice.getBestPrice( partKey, int(1)) if best_Price == None: logging.error('Error, Best Price not determined. ') raise Exception('Best Price not determined.') if not productModel or not best_Price: logging.error('Error, No Product Model Found ') raise Exception('No Product Model Found using urlsafe key and the function getBestPrice') params = {'product': productModel, 'best_price': dollar_float(float(best_Price)), } self.bournee_template('createAlertForm.html', **params) except Exception as e: logging.error('Error, in CreateAlertFormHandler: -- %s' % str(e)) message = _('We are having difficulties with the request for the Alert Form. Please try again later.') self.add_message(message, 'error') try: self.redirect(self.request.referer) except: self.redirect_to('home')
def doWork(self, partKey, quantity): """ This is a common function for both Methods GET and POST """ productModel = None best_price = None try: ##: Make Sure quantity from URL is an integer qnt = int(quantity) logging.info('Quantity suplied in CreateLimitOrderFormHandler = %s' % str(qnt)) ##: Get the Product Model and Best Price ##: partKey is a urlSafe key from the request URL productModel, best_price = bestPrice.getBestPrice( partKey, int(qnt)) if best_price == None: logging.error('Error, Best Price not determined. ') raise Exception('Best Price not determined.') if not productModel or not best_price: logging.error('Error, No Product Model Found ') raise Exception('No Product Model Found using urlsafe key and the function getBestPrice') params = {'product': productModel, 'requested_quantity': int(qnt), 'best_price': dollar_float(float(best_price)), } self.bournee_template('limitOrder.html', **params) except Exception as e: logging.error('Error, Updating Quantity for CreateLimitOrderFormHandler: -- %s' % str(e)) message = _('We are having difficulties with the request for the Limit Order Form. Please try again later.') self.add_message(message, 'error') try: self.redirect(self.request.referer) except: self.redirect_to('home')
def getTestProduct(self): self.testapp.reset() product, best_price = bestPrice.getBestPrice(None, str("AVE106M16B12T-F"), int(1)) if product: productPriceTiers = self.getProductPriceTiers_withoutURLOPEN(product) return product, best_price, productPriceTiers else: self.fail("getBestPrice failed during function getTestProduct")
def post(self): try: if not self.addProduct_form.validate(): raise Exception('addProduct_form did not Validate, in function POST of GetProductFormHandler') logging.info("addProduct_form Form Was valid") best_price = None productModel = None quantity = 1 ##: Try to fetch the data from the Form responce productNumber = str(self.addProduct_form.productNumber.data).strip() ##: Product Number urlsafeSellerKey = str(self.addProduct_form.urlsafeSellerKey.data).strip() ##: Urlsafe Seller Key urlsafeCartKey = str(self.request.POST.get('ck', None)).strip() ##: Urlsafe Cart Key Optional qnt = self.request.POST.get('qnt', None) ##: Urlsafe Seller Key logging.info('here') if qnt: try: quantity = int(qnt) except: logging.error('The quantity supplied in the form submission could not be converted into an integer') message = _('Sorry, the quantity supplied in the form submission was not valid. Please try again later.') self.add_message(message, 'error') try: self.redirect(self.request.referer) except: self.redirect_to('home') cleanProductNUmber = utils.clean_product_number(productNumber) logging.info('here') sellerKey = ndb.Key(urlsafe=urlsafeSellerKey) productKey = ndb.Key(shoppingModels.Product, cleanProductNUmber, parent=sellerKey) productModel = productKey.get() if not productModel: logging.info('here') ######################################################################## ################# ######## We don't have this product yet so we must Parse the website. ################# ######################################################################## try: sellerModel = ndb.Key(urlsafe=urlsafeSellerKey).get() logging.info('here') if not sellerModel: raise Exception('Seller of requested product was not found.') if sellerModel.parser == 'DIGIKEY': # Call to parser logging.info('Product Number to search: {}'.format(productNumber)) productModel, best_price_cents = parsers.DK_Search(sellerModel, str(productNumber), int(quantity)) else: raise Exception('At this time we cannot get product info from Seller') # Check over results of Parser if not productModel: raise Exception('Missing a productModel from the parser response') if not best_price_cents: raise Exception('Missing a best_price_cents from the parser response') best_price = float(best_price_cents)/100 # convert to dollars except Exception as e: logging.error('Error creating a productModel: -- {}'.format(e)) message = _('Sorry, we could not retrieve your product request. Please try again later.') self.add_message(message, 'error') try: return self.redirect(self.request.referer) except: return self.redirect_to('home') ##: A Product Model was found else: logging.info('here') ######################################################################## ################# ######## Send to bestPrice script ################# ######################################################################## try: best_price = bestPrice.getBestPrice(productModel.key.urlsafe(), int(quantity)) if not best_price: raise Exception('Best price returned None for product number: {}'.format(productModel.pn)) except Exception as e: logging.error('Error finding Product and/or Price in function getProduct of ProductRequestHandler : %s' % e) message = _('Sorry, we could not find a price result for your product request. Please try again later.') self.add_message(message, 'error') try: return self.redirect(self.request.referer) except: return self.redirect_to('home') if not productModel or not best_price: raise Exception('Either the productModel or the best_price is missing') if urlsafeCartKey: logging.info('here') old_order_subtotal = 0 cartModel = ndb.Key(urlsafe=urlsafeCartKey).get() if not cartModel: raise Exception('cartModel was not found using the urlsafeCartKey given in the form.') ##: Check to see if user already created this Order within this Cart currentOrder = shoppingModels.Order.get_for_product_and_cart(cartModel.key, str(productModel.pn)) newOrder = None ##: Create or Update the Order Model if currentOrder: logging.info('here') old_order_subtotal = currentOrder.st ##: must record the old subTotal before updating the QNT newOrder = currentOrder.update_order_add_qnt(currentOrder, int(quantity), put_model=False) else: logging.info('here') old_order_subtotal = 0 newOrder = shoppingModels.Order.create_order(cartModel.key, productModel.key, int(quantity), put_model=False) ##: Update the Cart for the Totals Costs if newOrder: ##: Updatte the Cart's subtotals orderSubTotal = (int(newOrder.st)-int(old_order_subtotal)) oldCartSubTotal = cartModel.st newCartSubTotal = int(oldCartSubTotal) + int(orderSubTotal) shoppingModels.Cart.update_subtotal_values(cartModel, newCartSubTotal, oldCartSubTotal, put_model=False) ndb.put_multi( [cartModel, newOrder] ) message = _('We have found the requested Product: {} and have added it to your cart {}.'.format(productModel.pn, cartModel.n)) self.add_message(message, 'success') else: message = _('We have saved the requested Product: {} to our database.'.format(productModel.pn)) self.add_message(message, 'success') except Exception as e: logging.error('Error finding or creating Product in function post of GetProductFormHandler : %s' % e) message = _('Sorry, there was an error getting the Product requested. Please try again later.') self.add_message(message, 'error') finally: logging.info('here') try: self.redirect(self.request.referer) except: self.redirect_to('home')
def doWork(self, productModel): """ This is a common function for both Methods GET and POST """ best_price = None qnt = self.request.get('q', 1) try: quantity = int(qnt) except: logging.error('Error, QNT supplied in request URI was not an integer: QNT = %s' % str(qnt)) raise Exception('Error, QNT supplied in request URI was not an integer: QNT = %s' % str(qnt)) try: ######################################################################## ################# ######## Send to bestPrice script ################# ######################################################################## try: best_price = bestPrice.getBestPrice(productModel.key.urlsafe(), int(quantity)) except Exception as e: logging.error('Error finding Product and/or Price in function getProduct of ProductRequestHandler : %s' % e) message = _('We could not find a Price result for your Product Request. Please try again later.') self.add_message(message, 'error') try: self.redirect(self.request.referer) except: self.redirect_to('home') ######################################################################## ################# ######## Check Results for None's ################# ######################################################################## if best_price == None or best_price <= 0.0: raise Exception('We could not find a Price result for your Product Request. Please try again later.') ## This is an error and we Need a Price to show the User logging.error("Best Price returned as None in function getProduct of ProductRequestHandler.") message = _('We could not find a Price result for your Product Request. Please try again later.') self.add_message(message, 'error') try: self.redirect(self.request.referer) except: self.redirect_to('home') ######################################################################## ##: Add this product to the last products viewed memcache ######################################################################## try: lpv = memcache.get('%s:lastProductsViewed' % str(self.request.remote_addr)) if lpv == None: lpv = [] if productModel in lpv: lpv.remove(productModel) if len(lpv)>10: lastItem = lpv.pop() lpv.insert(0,productModel) memcache.set('%s:lastProductsViewed' % str(self.request.remote_addr),lpv) except Exception as e: logging.error('Error setting Memcache for lastProductsViewed in class ProductRequestHandler : %s' % e) ######################################################################## ##: This is the analytics counter for an idividual product ######################################################################## try: counter.load_and_increment_counter(name=productModel.key.urlsafe(), period_types=[counter.PeriodType.ALL,counter.PeriodType.YEAR], namespace="products") except Exception as e: logging.error('Error setting LiveCount for product in class ProductRequestHandler : %s' % e) params = { 'product': productModel, 'best_price': utils.dollar_float(float(best_price)), 'requested_quantity': int(quantity), 'total_cost': utils.dollar_float(float(best_price)*float(quantity)) } self.bournee_template('product.html', **params) except Exception as e: logging.error('Error finding Product and/or Price in function doWork of ProductRequestHandler : %s' % e) message = _('We could not find a Price result for your Product Request. Please try again later.') self.add_message(message, 'error') try: self.redirect(self.request.referer) except: self.redirect_to('home')
def post(self): try: if not self.addToCart_form.validate(): raise Exception('addToCart_form did not Validate, in function \ POST of AddToCartHandler') logging.info("addToCart_form Form Was valid") order = None cart = None cartName = None urlsafeCartKey = None old_order_subtotal = 0 ##: Try to fetch the data from the Form responce urlsafeProductKey = str(self.addToCart_form.pk.data).strip() cartName = str(self.addToCart_form.cn.data).strip().upper() urlsafeCartKey = str(self.addToCart_form.ck.data).strip() qnt = self.addToCart_form.q.data ##: Quantity logging.info("{}, {}".format(urlsafeCartKey, type(urlsafeCartKey))) logging.info("{}, {}".format(cartName, type(cartName))) ##: This is important for when user selects a cart to use for adding product and wished to creat a new private cart. if urlsafeCartKey == 'None' and cartName == '': urlsafeCartKey = None cartName = 'SHOPPING' logging.info("{}, {}".format(cartName, type(cartName))) ##: Try to find the part in the Datastore and get Best Price. productModel, orderPrice = bestPrice.getBestPrice(urlsafeProductKey, int(qnt), returnProductModel=True) if productModel: logging.info("Found a productModel") ##: Initialize a variable for orderPrice with the part's current Best Unit Price if not orderPrice: orderPrice = int(productModel.bup) else: orderPrice = int(orderPrice*100) logging.info("Best Price so far in AddToCartHandler : %s -- (This should be an integer)" % str(orderPrice)) ##: Get or create the Cart cart = shoppingModels.Cart.get_or_create_cart(self.user_key, urlsafeCartKey=urlsafeCartKey , cartName=str(cartName)) if not cart: logging.info("Did not Find a Cart") raise Exception('No Cart returned, error creating Cart, in function POST of AddToCartHandler') ##: Check to see if user already created this Order within this Cart currentOrder = shoppingModels.Order.get_for_product_and_cart(cart.key, str(productModel.pn)) ##: Create or Update the Order Model if currentOrder: old_order_subtotal = currentOrder.st ##: must record the old subTotal before updating the QNT order = currentOrder.update_order_add_qnt(currentOrder, int(qnt), put_model=False) else: order = shoppingModels.Order.create_order(cart.key, productModel.key, int(qnt), put_model=False) ##: Update the Cart for the Totals Costs if order: ##: Updatte the Cart's subtotals orderSubTotal = (int(order.st)-int(old_order_subtotal)) oldCartSubTotal = cart.st newCartSubTotal = int(oldCartSubTotal) + int(orderSubTotal) shoppingModels.Cart.update_subtotal_values(cart, newCartSubTotal, oldCartSubTotal, put_model=False) ndb.put_multi( [cart, order] ) logging.info("We have a order_key and a cart_key so Success and Redirect") message = _('Submission request successful for Product number - %s' % str(productModel.pn)) self.add_message(message, 'success') else: raise Exception('No keys returned, error creating Cart/Order Item, in function POST of AddToCartHandler') except Exception as e: logging.error('Error in function POST of AddToCartHandler : -- %s' % e) message = _('We are having difficulties with finalizing the Order Submission. Please try again later.') self.add_message(message, 'error') finally: logging.info('Finished now Redirect to Referrer') try: self.redirect(self.request.referer) except: self.redirect_to('home')