def get_products(): resource = '/Products' try: client = ApiClient(URI, HEADERS, USERNAME, PASSWORD) while True: response = client.GET(resource) if response.status_code == 200 and response.is_json: products = Products(response.json) for product in products: print("{0:38} {1:40} {2:20} {3}".format( product.id, product.Description[:40] if product.Description != None else '', product.SearchName[:20] if product.SearchName != None else '', product.Price)) else: print("response error: %d - %s" % (response.status_code, response.text)) # paging resource = response.next_link if (resource == None or response.status_code != 200): break except ValueError: print("Unexpected data: ", response.text) except: print("Unexpected error:", sys.exc_info()[0])
def test_get_products(self): """test get method for products""" sample_product_from_db = {'name': 'breakfast burrito', 'cost': 2.02, 'ingredients': 'eggs, flour tortilla, refried beans'} product_instance = Products() test = product_instance.get_products() self.assertEqual(test[0], sample_product_from_db)
def delete_product(): if request.method == 'POST': name = request.form['product-name'] product_instance = Products() product_instance.delete_product(name) return redirect('/products') else: return render_template('delete_product.html')
def crawl_products(): try: products = Products() products = products.go(request.args.get('url')) return jsonify(products) except Exception as e: resp = jsonify({'errcode': 500, 'errmsg': '抓取产品列表异常: ' + str(e)}) resp.status_code = 500 return resp
def add_new_product(): if request.method == 'POST': name = request.form['product-name'] cost = request.form['product-cost'] ingredients = request.form['product-ingredients'] product_instance = Products() product_instance.add_product(name, cost, ingredients) return redirect('/products') else: return render_template('add_new_product.html')
def test_add_product(self): """test add product method for products""" product_to_add = {'name': 'cucumber', 'cost': 5.55, 'ingredients': None} product_instance = Products() # method should return object added if successful test = product_instance.add_product(product_to_add["name"], product_to_add["cost"], product_to_add["ingredients"]) self.assertEqual(test, product_to_add) # method should return 0 if object already exists product_to_add_key_already_exists = {'name': 'chips', 'cost': 2.22, 'ingredients': None} test2 = product_instance.add_product(product_to_add_key_already_exists["name"], product_to_add_key_already_exists["cost"], product_to_add_key_already_exists["ingredients"]) self.assertEqual(test2, 0)
def test_delete_product(self): """test delete product method for products""" product_key_to_delete = 'cucumber' product_instance = Products() # method should return object added if successful test = product_instance.delete_product(product_key_to_delete) self.assertEqual(test, {'name': product_key_to_delete}) # method should return 0 if the key does not exist product_key_to_delete_2 = 'apple pie' test2 = product_instance.delete_product(product_key_to_delete_2) self.assertEqual(test2, 0)
def predict(receipt): ## predict vendor vendor = Vendor(receipt.rawText, receipt.lines) vendor.run() receipt.ruleBasedPrediction['vendor'] = vendor._result ## predict tax rate taxRate = TaxRate(receipt.rawText, receipt.lines, receipt.graph, receipt.words) taxRate.run() receipt.ruleBasedPrediction['tax_rate'] = taxRate._result ## predict total price totalPrice = TotalPrice(receipt.rawText, receipt.lines) totalPrice.run() receipt.ruleBasedPrediction['total_price'] = totalPrice._result ## predict date date = Date(receipt.rawText, receipt.lines) date.run() receipt.ruleBasedPrediction['date'] = date._result ## predict currency currency = Currency(receipt.rawText) currency.run() receipt.ruleBasedPrediction['currency'] = currency._result ## predict address address = Address(receipt.linesText) address.run() receipt.ruleBasedPrediction['address'] = address._result ## predict products products = Products(receipt.rawText, receipt.lines, receipt.linesText) products.run() receipt.ruleBasedPrediction['products'] = products._result
def delete(self): url = self.request.uri route = url.split('/') status_int = 200 if 'cart' in route: uid = route[len(route) - 1] cart = Cart() items = Items() cart_id = cart.removeCart(uid=uid) if cart_id != '': items.removeItems(cart_id=cart_id) response_data = { 'message': 'successfully deleted cart', 'cart': {} } else: response_data = { 'message': 'cart not found', 'cart': {} } elif 'transactions' in route: id = route[len(route) - 1] uid = route[len(route) - 2] this_transactions = Transactions() transaction_list = this_transactions.removeTransaction(id=id,uid=uid) response_data = [] for transaction in transaction_list: response_data.append(transaction.to_dict()) elif 'products' in route: id = route[len(route) - 1] uid = route[len(route) - 2] this_product = Products() result = this_product.deleteProduct(uid=uid,id=id) if result != '': response_data = result.to_dict() else: status_int = 401 response_data = {'message':'product not found'} elif 'dashboard' in route: uid = route[len(route) - 2] user_request = User.query(User.uid == uid) user_list =user_request.fetch() response_data = [] if len(user_list) > 0: user = user_list[0] if ('banking' in route) and ('delete' in route) and user.is_admin: # routes.api_dashboard_endpoint + `/banking/delete/${uid}/${banking_id} banking_id = route[len(route) - 1] this_banking = Banking() result = this_banking.deleteBanking(banking_id=banking_id) if result == True: banking_query = Banking.query() banking_list = banking_query.fetch() for banking in banking_list: response_data.append(banking.to_dict()) else: status_int = 403 response_data = {'message': 'bank account record not found'} #TODO add more adminstrative tasks here else: status_int = 401 response_data = {'message': 'your request is not understood'} else: status_int = 401 response_data = {'message': 'your request is not understood'} else: status_int = 403 response_data = { 'message' : 'error resource not found' } self.response.headers['Content-Type'] = "application/json" self.response.status_int = status_int json_data = json.dumps(response_data) self.response.write(json_data)
from flask import Flask, render_template, request from products import Products app = Flask(__name__) db = Products() @app.route("/") def products(): return render_template("products.html", products=db.products) @app.route("/search", methods=["GET", "POST"]) def search(): if request.method == "GET": return render_template("form.html") elif request.method == "POST": hasresults = False output = [] if request.form["name"] != "": output = db.findbyName(request.form["name"]) elif request.form["price"] != "": output = db.findbyPrice(request.form["price"]) elif request.form["qty"] != "": output = db.findbyQty(request.form["qty"]) if len(output) > 0: hasresults = True else:
#!/usr/bin/env python3 import pyhop2 from a_star import astar from gbfs import gbfs from map import Map from renderer import Renderer from robot_path_controller.srv import Path, PathResponse from robot_path_controller.msg import WayPoint import rospy from gazebo_msgs.srv import GetModelState from check_result import check_result, pause, set_trace from products import Products import numpy as np prod = Products() prod.seed(1) item_list = prod.get_random_list() item_list.append('cashier') renderer = Renderer() ######################################################### ## Grocery Plan ######################################### # loc = {'robot': (7.4, 12.85), 'brocoli': (1.54, 5.4), 'cucumber': (1.54, 7.91), 'salt': (8.39, 4.79), 'watermelon': (5.1, 8.44), 'strawberry': (2.31, 6.36), 'potato': (3.58, 7.44), 'hamburger': (7.4, 12.85)} domain_name = 'groceryplan' # Create a new domain to contain the methods and operators pyhop2.Domain(domain_name)
def put(self): url = self.request.uri route = url.split('/') status_int = 200 logging.info('ARE WE THERE YET') if 'coupons' in route: json_data = json.loads(self.request.body) logging.info(json_data) coupons_request = Coupons.query(Coupons.code == json_data['code'] and Coupons.valid == True) coupons_list = coupons_request.fetch(); cart_request = Cart.query(Cart.uid == json_data['uid']) cart_list = cart_request.fetch() if ((len(coupons_list) > 0) and (len(cart_list > 0))): coupon = coupons_list[0] coupon_code = coupon.to_dict() response_data = { 'succeed' : True, 'coupon' : coupon_code, 'message' : 'coupon code valid' } else: response_data = { 'succeed': False, 'coupon' : {}, 'message':'cannot find coupon or your cart is empty' } elif 'user' in route: json_data = json.loads(self.request.body) logging.info(json_data) this_user = User(); this_user = this_user.updateUser(json_user=json_data) if this_user != '': response_data = this_user.to_dict() else: status_int = 403 response_data={'message':'user not found'} elif 'services' in route: json_data = json.loads(self.request.body) this_service = Services() this_service = this_service.updateService(service=json_data) if this_service != '': response_data = this_service.to_dict() else: status_int = 403 response_data = {'message': 'error updating service'} elif 'products' in route: json_data = json.loads(self.request.body) this_product = Products() this_product = this_product.updateProduct(product=json_data) if this_product != '': response_data = this_product.to_dict() else: status_int = 403 response_data = {'message': 'error updating product'} elif 'transactions' in route: json_data = json.loads(self.request.body); # do process transaction here and create an alert to show that transction # must be processed elif 'payments' in route: if 'approve' in route: uid = str(route[len(route) - 1]) transaction = json.loads(self.request.body) this_user = User() this_user = this_user.getUser(uid=uid) if this_user.is_admin: this_transaction_request = Transactions.query(Transactions.id == transaction['id']) this_transaction_list = this_transaction_request.fetch() if len(this_transaction_list) > 0: this_transaction = this_transaction_list[0] this_transaction.processed = True this_transaction.put() response_data = this_transaction.to_dict() else: status_int = 401 response_data = {'message': 'transaction not found'} else: status_int = 403 response_data = {'message': 'you are not authorized to perform this action'} elif 'reject' in route: uid = str(route[len(route) - 1]) transaction = json.loads(self.request.body) this_user = User() this_user = this_user.getUser(uid=uid) if this_user.is_admin: this_transaction_request = Transactions.query( Transactions.id == transaction['id']) this_transaction_list = this_transaction_request.fetch() if len(this_transaction_list) > 0: this_transaction = this_transaction_list[0] this_transaction.processed = False this_transaction.put() response_data = this_transaction.to_dict() else: status_int = 401 response_data = {'message': 'transaction not found'} else: status_int = 403 response_data = { 'message': 'you are not authorized to perform this action'} # add more sub actions here else: status_int = 501 response_data = {'message': 'we do not understand that request'} elif 'dashboard' in route: uid = route[len(route) - 1]; # finding admin user information admin_request = User.query(User.uid == uid) admin_list = admin_request.fetch() if len(admin_list) > 0: user = admin_list[0] else: user = User() response_data = '' if ('user' in route) and user.is_admin: user_data = json.loads(self.request.body) user_request = User.query(User.uid == user_data['uid']) user_list = user_request.fetch() if(len(user_list) > 0): user = user_list[0] user = user.updateUser(json_data=user_data) response_data = user.to_dict() else: status_int = 403 response_data = {'message':'user not found'} else: status_int = 402 response_data = {'message': 'request malformed'} else: status_int = 401 response_data = {'message': 'you are not allowed to access that method'} self.response.headers['Content-Type'] = "application/json" self.response.status_int = status_int json_data = json.dumps(response_data) self.response.write(json_data)
from products import Products from store import Store apple = Products({"category": "fruit", "name": "apple", "price": .5}) orange = Products({"category": "fruit", "name": "orange", "price": .8}) banana = Products({"category": "fruit", "name": "banana", "price": .6}) carrot = Products({"category": "vegetable", "name": "carrot", "price": 1}) potato = Products({"category": "vegetable", "name": "potato", "price": 2}) onion = Products({"category": "vegetable", "name": "onion", "price": 1.5}) hat = Products({"category": "clothing", "name": "hat", "price": 10}) boots = Products({"category": "clothing", "name": "boots", "price": 20}) gloves = Products({"category": "clothing", "name": "gloves", "price": 6}) store_1 = Store("Bob's Store") store_2 = Store("Bill's Store") store_1.add_product(apple).add_product(carrot).add_product(gloves).add_product( onion).list_of_inventory() store_1.sell_product(3).list_of_inventory().inflation( .2).list_of_inventory().set_clearance("clothing", .1).list_of_inventory()
def __init__(self, radius=0.177, clearance=0.15): super().__init__(radius, clearance) self.blank_image = np.ones(shape=[1400, 1600, 3], dtype=np.uint8) self.font = cv2.FONT_ITALIC self.products = Products() self.cashier_coord = (1465.5536, 1400 - 304.2128) distance = (radius + clearance) * 100 boundrec1 = np.array( [[[0, 1400], [0, 1400 - 476.5123], [119.9979, 1400 - 476.5123], [119.9979, 1400 - 974.8759], [113.0248, 1400 - 1093.9484], [326.3999, 1400 - 1215.5476], [803.7341, 1400 - 1345.3712], [1052.8966, 1400 - 1345.3712], [1161.2505, 1400 - 1301.1247], [1505.3117, 1400 - 953.9164], [1544.8179, 1400 - 891.2024], [1544.8179, 1400]]], np.int32) cv2.fillConvexPoly(self.blank_image, boundrec1, (255, 255, 255)) x1 = ((self.line2.coeff[1] - self.line1.coeff[1]) / (self.line1.coeff[0] - self.line2.coeff[0])) y1 = (x1 * self.line1.coeff[0] + self.line1.coeff[1]) x2 = ((self.line3.coeff[1] - self.line2.coeff[1]) / (self.line2.coeff[0] - self.line3.coeff[0])) y2 = (x2 * self.line2.coeff[0] + self.line2.coeff[1]) x2 = ((self.line3.coeff[1] - self.line2.coeff[1]) / (self.line2.coeff[0] - self.line3.coeff[0])) * 100 y2 = (x2 / 100 * self.line2.coeff[0] + self.line2.coeff[1]) * 100 boundrec2 = np.array( [[[0 + distance, 1400 - distance], [0 + distance, 1400 - 476.5123 + distance], [119.9979 + distance, 1400 - 476.5123 + distance], [119.9979 + distance, 1400 - 974.8759], [x1 * 100, 1400 - y1 * 100], [x2 * 100, 1400 - y2 * 100], [803.7341, 1400 - 1345.3712 + distance], [1052.8966, 1400 - 1345.3712 + distance], [1161.2505, 1400 - 1301.1247], [1505.3117, 1400 - 953.9164], [1544.8179 - distance, 1400 - 891.2024], [1544.8179 - distance, 1400 - distance]]], np.int32) cv2.fillConvexPoly(self.blank_image, boundrec2, (211, 211, 211)) # Cashiers cashier1_d = np.array( [[[525.1926 - distance, 1400 - 224.6674 + distance], [525.1926 - distance, 1400 - 369.3339 - distance], [603.5216 + distance, 1400 - 369.3339 - distance], [603.5216 + distance, 1400 - 224.6674 + distance]]], np.int32) cashier2_d = np.array( [[[717.2170 - distance, 1400 - 224.6674 + distance], [717.2170 - distance, 1400 - 369.3339 - distance], [797.5383 + distance, 1400 - 369.3339 - distance], [797.5383 + distance, 1400 - 224.6674 + distance]]], np.int32) cashier3_d = np.array( [[[904.0226 - distance, 1400 - 224.6674 + distance], [904.0226 - distance, 1400 - 369.3339 - distance], [983.2662 + distance, 1400 - 369.3339 - distance], [983.2662 + distance, 1400 - 224.6674 + distance]]], np.int32) cashier4_d = np.array( [[[1093.1436 - distance, 1400 - 224.6674 + distance], [1093.1436 - distance, 1400 - 369.3339 - distance], [1175.5313 + distance, 1400 - 369.3339 - distance], [1175.5313 + distance, 1400 - 224.6674 + distance]]], np.int32) cashier5_d = np.array( [[[1283.3400 - distance, 1400 - 224.6674 + distance], [1283.3400 - distance, 1400 - 369.3339 - distance], [1364.6369 + distance, 1400 - 369.3339 - distance], [1364.6369 + distance, 1400 - 224.6674 + distance]]], np.int32) cv2.fillPoly(self.blank_image, cashier1_d, (255, 255, 255)) cv2.fillPoly(self.blank_image, cashier2_d, (255, 255, 255)) cv2.fillPoly(self.blank_image, cashier3_d, (255, 255, 255)) cv2.fillPoly(self.blank_image, cashier4_d, (255, 255, 255)) cv2.fillPoly(self.blank_image, cashier5_d, (255, 255, 255)) cashier1 = np.array( [[[525.1926, 1400 - 224.6674], [525.1926, 1400 - 369.3339], [603.5216, 1400 - 369.3339], [603.5216, 1400 - 224.6674]]], np.int32) cashier2 = np.array( [[[717.2170, 1400 - 224.6674], [717.2170, 1400 - 369.3339], [797.5383, 1400 - 369.3339], [797.5383, 1400 - 224.6674]]], np.int32) cashier3 = np.array( [[[904.0226, 1400 - 224.6674], [904.0226, 1400 - 369.3339], [983.2662, 1400 - 369.3339], [983.2662, 1400 - 224.6674]]], np.int32) cashier4 = np.array( [[[1093.1436, 1400 - 224.6674], [1093.1436, 1400 - 369.3339], [1175.5313, 1400 - 369.3339], [1175.5313, 1400 - 224.6674]]], np.int32) cashier5 = np.array( [[[1283.3400, 1400 - 224.6674], [1283.3400, 1400 - 369.3339], [1364.6369, 1400 - 369.3339], [1364.6369, 1400 - 224.6674]]], np.int32) cv2.fillPoly(self.blank_image, cashier1, (0, 0, 0)) cv2.fillPoly(self.blank_image, cashier2, (0, 0, 0)) cv2.fillPoly(self.blank_image, cashier3, (0, 0, 0)) cv2.fillPoly(self.blank_image, cashier4, (0, 0, 0)) cv2.fillPoly(self.blank_image, cashier5, (0, 0, 0)) #Circles cv2.circle(self.blank_image, (341, 1400 - 578), 78 + int(distance), (255, 255, 255), -1) cv2.circle(self.blank_image, (341, 1400 - 578), 78, (0, 0, 0), -1) # Shelves shelf1_d = np.array( [[[625.3904 - distance, 1400 - 1076.4730 - distance], [625.3904 - distance, 1400 - 977.5013 + distance], [960.5268 + distance, 1400 - 977.5013 + distance], [960.5268 + distance, 1400 - 1076.4730 - distance]]], np.int32) shelf1 = np.array( [[[625.3904, 1400 - 1076.4730], [625.3904, 1400 - 977.5013], [960.5268, 1400 - 977.5013], [960.5268, 1400 - 1076.4730]]], np.int32) cv2.fillPoly(self.blank_image, shelf1_d, (255, 255, 255)) cv2.fillPoly(self.blank_image, shelf1, (0, 0, 0)) shelf2_d = np.array( [[[625.3904 - distance, 1400 - 620.9282 - distance], [625.3904 - distance, 1400 - 526.6344 + distance], [960.5268 + distance, 1400 - 526.6344 + distance], [960.5268 + distance, 1400 - 620.9282 - distance]]], np.int32) shelf2 = np.array( [[[625.3904, 1400 - 620.9282], [625.3904, 1400 - 526.6344], [960.5268, 1400 - 526.6344], [960.5268, 1400 - 620.9282]]], np.int32) cv2.fillPoly(self.blank_image, shelf2_d, (255, 255, 255)) cv2.fillPoly(self.blank_image, shelf2, (0, 0, 0)) shelf3_d = np.array( [[[625.3904 - distance, 1400 - 843.2007 - distance], [625.3904 - distance, 1400 - 750.5381 + distance], [722.7457 + distance, 1400 - 750.5381 + distance], [722.7457 + distance, 1400 - 843.2007 - distance]]], np.int32) shelf3 = np.array( [[[625.3904, 1400 - 843.2007], [625.3904, 1400 - 750.5381], [722.7457, 1400 - 750.5381], [722.7457, 1400 - 843.2007]]], np.int32) cv2.fillPoly(self.blank_image, shelf3_d, (255, 255, 255)) cv2.fillPoly(self.blank_image, shelf3, (0, 0, 0)) shelf4_d = np.array( [[[862.2844 - distance, 1400 - 843.2007 - distance], [862.2844 - distance, 1400 - 750.5381 + distance], [961.0721 + distance, 1400 - 750.5381 + distance], [961.0721 + distance, 1400 - 843.2007 - distance]]], np.int32) shelf4 = np.array( [[[862.2844, 1400 - 843.2007], [862.2844, 1400 - 750.5381], [961.0721, 1400 - 750.5381], [961.0721, 1400 - 843.2007]]], np.int32) cv2.fillPoly(self.blank_image, shelf4_d, (255, 255, 255)) cv2.fillPoly(self.blank_image, shelf4, (0, 0, 0)) shelf5_d = np.array( [[[270.2442 - distance, 1400 - 882.7066 - distance], [270.2442 - distance, 1400 - 784.6692 + distance], [392.6082 + distance, 1400 - 784.6692 + distance], [392.6082 + distance, 1400 - 882.7066 - distance]]], np.int32) shelf5 = np.array( [[[270.2442, 1400 - 882.7066], [270.2442, 1400 - 784.6692], [392.6082, 1400 - 784.6692], [392.6082, 1400 - 882.7066]]], np.int32) cv2.fillPoly(self.blank_image, shelf5_d, (255, 255, 255)) cv2.circle(self.blank_image, (393, 1400 - 835), 70 + int(distance), (255, 255, 255), -1) cv2.fillPoly(self.blank_image, shelf5, (0, 0, 0)) cv2.circle(self.blank_image, (393, 1400 - 835), 70, (0, 0, 0), -1) shelf6_d = np.array( [[[1316.0530 - distance, 1400 - 616.5968 - distance], [1316.0530 - distance, 1400 - 468.7012 + distance], [1393.9310 + distance, 1400 - 468.7012 + distance], [1393.9310 + distance, 1400 - 616.5968 - distance]]], np.int32) shelf6 = np.array( [[[1316.0530, 1400 - 616.5968], [1316.0530, 1400 - 468.7012], [1393.9310, 1400 - 468.7012], [1393.9310, 1400 - 616.5968]]], np.int32) cv2.fillPoly(self.blank_image, shelf6_d, (255, 255, 255)) cv2.fillPoly(self.blank_image, shelf6, (0, 0, 0)) shelf6_d = np.array( [[[1097.8244 - distance, 1400 - 968.7450 - distance], [1097.8244 - distance, 1400 - 632 + distance], [1197.4152 + distance, 1400 - 632 + distance], [1197.4152 + distance, 1400 - 968.7450 - distance]]], np.int32) shelf6 = np.array( [[[1097.8244, 1400 - 968.7450], [1097.8244, 1400 - 632], [1197.4152, 1400 - 632], [1197.4152, 1400 - 968.7450]]], np.int32) cv2.fillPoly(self.blank_image, shelf6_d, (255, 255, 255)) cv2.fillPoly(self.blank_image, shelf6, (0, 0, 0))
from flask import Flask, render_template, jsonify, request, Blueprint from flask_paginate import Pagination, get_page_parameter, get_page_args from urllib import parse import contentful from forms import SearchBar from math import ceil from products import Products from decouple import config get_products = Products() app = Flask(__name__) app.config['SECRET_KEY'] = config('SECRET_KEY') # mod = Blueprint('product_page', __name__) # app.register_blueprint(mod) @app.template_filter('get_image') def get_image(input): try: return input.image[0]['secure_url'] except AttributeError: pass @app.route('/') def home(): products = get_products.get_discount_items()
return self def sell_product(self, id): self.products.remove(self.products[id]) return self def inflation(self, percent_increase): self.products.price = Products.update_price(percent_increase, True) def set_clearance(self, category, percent_discount): pass myStore = Store("Michael's Store") myShirt = Products("Shirt", 30, "Top") myPants = Products("Jeans", 50, "Bottoms") myHat = Products("Hat", 25, " Hat") myStore.add_product(myShirt).add_product(myPants).add_product(myHat) myStore.sell_product(0) myStore.inflation(10) # print(myStore.products) def print_products_list(): for product_list in myStore.products: print(product_list.name, product_list.price, product_list.category)
from product import Product from products import Products from order import Order from orders import Orders import pickle products = None orders = None try: f = open('data.pkl', 'rb') except IOError: print 'Cannot open file!!!' products = Products() orders = Orders() data = {} else: data = pickle.load(f) products = Products(data['products'], data['plast']) orders = Orders(data['orders']) f.close() if not products.empty(): print 'Data has been loaded' else: print 'File has been found, but it has any data' def select_menu(): print "\n1. 'products'\n2. 'orders'\n3. Back" while True: key = raw_input("Select table: ")
def post(self): url = self.request.uri route = url.split('/') status_int = 200 if 'contact' in route: json_data = json.loads(self.request.body) logging.info(json_data) this_contact = Contact() contact_key = this_contact.new_contact(contact=json_data) if contact_key != None: response_data = {'message': 'Thank you ' + str(json_data['names']) + ' for sending us this message we will be responding to you through this email ' + str(json_data['email']) } else: response_data = {'message' : 'Unfortunately we cannot process any more contact messages from you'} elif 'categories' in route: json_data = json.loads(self.request.body) this_category = Categories(); this_category = this_category.addCategory(category=json_data) if this_category == '': status_int = 403 response_data={'message':'error category already exist'} else: response_data = this_category.to_dict() elif 'products' in route: json_data = json.loads(self.request.body) this_products = Products() this_products = this_products.addProduct(product=json_data) logging.info(this_products) if this_products != None: response_data = {'message': 'product successfully added'} else: response_data = {'message': 'duplicate product error'} elif 'services' in route: json_data = json.loads(self.request.body) this_service = Services() this_service = this_service.addService(service=json_data) if this_service != '': response_data = this_service.to_dict() else: status_int = 403 response_data = { 'message':'duplicate service'} elif 'physical-address' in route: json_data = json.loads(self.request.body) physical_address = PhysicalAddress() physical_address = physical_address.addPhysicalAddress(physical=json_data) response_data = physical_address.to_dict() elif 'contact-details' in route: json_data = json.loads(self.request.body) contact_details = ContactDetails() contact_details = contact_details.addContactDetails(contact=json_data) response_data = contact_details.to_dict() elif 'cart' in route: json_data = json.loads(self.request.body) cart_owner_id = json_data['uid'] item = json_data['item'] logging.info(item) cart_request = Cart.query(Cart.uid == cart_owner_id) cart_list = cart_request.fetch() if len(cart_list) > 0 : cart = cart_list[0] else: cart = Cart() cart.uid = cart_owner_id cart.cart_id = cart.create_cart_id() cart.is_active = True today = datetime.now() today = today.strftime("%d-%b-%Y") cart.date_created = today cart.sub_total = str(0) cart.tax = str(0) cart.total = str(0) items = Items() try: product_name = item['product_name'] items.item_type = 'products' items.quantity = str(json_data['quantity']) except: items.item_type = 'services' items.quantity = str(json_data['quantity']) items.item_id = items.create_item_id() items.id_service_product = item['id'] items.cart_id = cart.cart_id items.price = item['price'] items.sub_total = str(float(items.price) * int(items.quantity)) cart.sub_total = str(float(cart.sub_total) + float(items.sub_total)) cart.tax = str(0) cart.total = str(float(cart.sub_total) + float(cart.tax)) cart.total_items = str(int(cart.total_items) + int(items.quantity)) cart.put() items.put() # add product to product requests and then add service to service requests if items.item_type == 'products': this_request = ProductRequests() this_request = this_request.addProduct(product=item,uid=cart_owner_id,total=items.quantity) else: this_request = ServiceRequests() this_request = this_request.addService(service=item,uid=cart_owner_id,total=items.quantity) items_request = Items.query(Items.cart_id == cart.cart_id) items_list = items_request.fetch() ser_items = [] for item in items_list: ser_items.append(item.to_dict()) cart = cart.to_dict() # let results = {status : true, cart_items : [], cart : {}, error: {} }; response_data = { 'status' : 'True' , 'cart_items': ser_items, 'cart' : cart, 'error' : {} } elif 'user' in route: json_data = json.loads(self.request.body) logging.info('User Data') logging.info(json_data) this_user = User() this_user = this_user.addUser(json_user=json_data) if this_user != '': response_data = this_user.to_dict() else: status_int = 403 response_data = {'message': 'user not found'} elif 'store' in route: json_data = json.loads(self.request.body) this_store = Store() this_store = this_store.addStore(store=json_data) if(this_store != ''): response_data = this_store.to_dict() else: status_int = 403 response_data = {'message': 'store not stored'} elif 'transactions' in route: json_data = json.loads(self.request.body) this_transaction = Transactions() result = this_transaction.addTransaction(transaction=json_data) logging.info(this_transaction) response_data = this_transaction.to_dict() elif 'sms' in route: uid = route[len(route) - 1] user = User() this_user = user.getUser(uid) if ('send' in route) and (this_user != ''): sms_message = json.loads(self.request.body) sms = SMSMessage() # once the message is sent results will be returned # through a webhook results = sms.addSMSmessage(sms_message=sms_message) response_data = {} response_data = results.to_dict() elif ('contact-lists' in route) and (this_user != ''): json_contact_lists = json.loads(self.request.body) contacts_lists = ContactLists() results = contacts_lists.addList(contact_list=json_contact_lists) response_data = {} response_data = results.to_dict() elif ('smscontact' in route) and (this_user != ''): json_contact = json.loads(self.request.body) logging.info(json_contact) sms_contact = SMSContacts() results = sms_contact.addContact(contact=json_contact) contact_list = sms_contact.fetchContactsByListID(id=json_contact['list_id']) response_data = [] for contact in contact_list: response_data.append(contact.to_dict()) else: status_int = 303 response_data = {'message':'request not understood'} elif 'dashboard' in route: uid = route[len(route) - 1] admin_user_query = User.query(User.uid == uid) admin_user_list = admin_user_query.fetch() response_data = '' if len(admin_user_list) > 0: admin_user = admin_user_list[0] if ('contact' in route) and admin_user.is_admin : if 'response' in route : response_message = json.loads(self.request.body) this_response = Response() results = this_response.createResponse(response_data=response_message, admin_user=admin_user) response_data = results.to_dict() else: status_int = 400 response_data = {'message': 'request could not be understood'} elif ('banking' in route) and admin_user.is_admin: banking_details = json.loads(self.request.body) this_banking = Banking() results = this_banking.addAdminBank(banking_details=banking_details) if (results != ''): response_data = results.to_dict() else: status_int = 401 response_data = {'message': 'error saving banking details'} else: status_int = 400 response_data = { 'message': 'request could not be understood'} else: status_int = 400 response_data = { 'message': 'request could not be understood'} else: status_int = 400 response_data = {'message': 'the server cannot process this request'} self.response.headers['Content-Type'] = "application/json" self.response.status_int = status_int json_data = json.dumps(response_data) self.response.write(json_data)
from products import Products from store import Store BuyLow = Store("BuyLow") MasonMart = Store("MasonMart") cereal = Products(2.50, "cereal", "breakfast") pastries = Products(3.50, "pastries", "breakfast") steak = Products(2.25, "steak", "meat") chicken = Products(2.00, "chicken", "meat") ham = Products(1.25, "ham", "meat") apple = Products(.50, "apple", "produce") banana = Products(.35, "banana", "produce") milk = Products(2.88, "milk", "dairy") cheese = Products(3.00, "cheese", "dairy") BuyLow.addProduct(cheese, "dairy") BuyLow.addProduct(milk, "dairy") BuyLow.addProduct(banana, "produce") BuyLow.addProduct(apple, "produce") BuyLow.addProduct(ham, "meat") BuyLow.addProduct(chicken, "meat") BuyLow.addProduct(steak, "meat") BuyLow.addProduct(pastries, "breakfast") BuyLow.addProduct(cereal, "breakfast") BuyLow.availableProducts("dairy") BuyLow.availableProducts("dairy")
def __init__(self): self.products = Products() self.pagination = Pagination() self.item = Item()
def products(): product_instance = Products() data = product_instance.get_products() return render_template('products.html', products=data)
from flask import Flask, jsonify, request, abort, make_response from products import Products from sales import Sales app = Flask(__name__) product = Products() sales = Sales() # Error Handling @app.errorhandler(400) def bad_request(error): return make_response(jsonify({'error': 'Bad Request'}), 400) @app.errorhandler(404) def not_found(error): return make_response(jsonify({'error': 'Server Not Found'}), 404) # Routes @app.route('/store_manager/api/v1/user/products', methods=['GET']) def get_products(): return jsonify({'products': product.get_all_products()}), 200 @app.route('/store_manager/api/v1/admin/products', methods=['POST']) def create_product(): return jsonify({'product': product.create_pdt()}), 201 @app.route('/store_manager/api/v1/user/products/<int:pdt_id>', methods=['GET']) def get_product(pdt_id): return jsonify({'product': product.get_pdt(pdt_id)}), 200
import sys, os from products import Products from orders import Orders from product import Product from order import Order from datetime import datetime import pickle products = Products() orders = Orders() menu_actions = {} memoryP = [] memoryO = [] index = 0 def main_menu(): os.system('clear') print ("Please choose the menu you want to start:") print ("1. Show products") print ("2. Enter products ") print ("3. Edit product ") print("4. Delete product") print("====================") print ("5. Show orders") print ("6. Make an order") print ("7. Edit order") print("8. Delete order") print("00. Search") print("11. pickle dump") print("22. pickle load") print ("\n0. Quit")