def retrieve(): list_link = "{}{}".format(BASE_URL, BOOK_LIST) html = retrieve_data("goodreads.top-books.html", list_link) soup = bs(html, "html.parser") rows = soup.find_all("tr", {"itemtype": "http://schema.org/Book"}) for row in rows[:100]: link = row.find("div", {"data-resource-type": "Book"}).a["href"] book_link = "{}{}".format(BASE_URL, link) fname = "{}.{}.html".format("goodreads", link_to_fname(link)) print("Fetching {}...".format(book_link)) html = retrieve_data(fname, book_link) try: soup = bs(html, "html.parser") title = soup.find("h1", {"id": "bookTitle"}).get_text() title = clean_whitespace(title) description = soup.select("div#description span")[-1].get_text() description = clean_whitespace(description) link = soup.find("a", {"id": "buyButton"})["href"] genres = soup.select(".left .bookPageGenreLink") genres = [clean_whitespace(genre.get_text()) for genre in genres] image = soup.find("img", {"id": "coverImage"})["src"] if not image.startswith("http"): image = "{}{}".format(BASE_URL, image) product = Product(title, "{}{}".format(BASE_URL, link), image, "books", genres, description) product.dump() except Exception as e: print("ERROR:", e) print("")
def listproductsAdmin(): error = False prod = Product() try: results = prod.listallAdmin() except (Exception) as err: error = True return handleError(err) finally: if not (error): return jsonify({'results': results})
def listtopsellers(): error = False prod = Product() try: results = prod.listTopSellers() except (Exception) as err: error = True return handleError(err) finally: if not (error): return jsonify({'results': results})
def getHighRatedProducts(): result = [] error = False try: prod = Product() result = prod.listHighRated() except (Exception) as err: error = True return handleError(err) finally: if not (error): return jsonify({'result': 'success', 'data': result})
def getProductReview(): error = False prod = Product() prod.id = request.json['id'] try: result = prod.listReviews() except (Exception) as err: error = True return handleError(err) finally: if not (error): return jsonify({'result': 'success', 'data': result})
def add_product(): print("***********") print("ADD PRODUCT") product_id = int(input("Enter product id: ")) product_name = input("Enter product name: ") product_price = float(input("Enter product price: ")) product_qty = int(input("Enter number of items in stock: ")) new_prod = Product(product_id, product_name, product_price, product_qty) if new_prod.has_errors() == False: datastore.add_product(new_prod) else: print("Product is not valid: ", new_prod.get_errors())
def getProduct(): error = False id = request.json['id'] new = Product() try: new.get(id) except (Exception) as err: error = True return handleError(err) finally: if not (error): result = new.json() return jsonify({'result': 'success', 'data': result})
def listproductsRecomended(): results = [] error = False prod = Product() prod.type = request.json['type'] prod.id = request.json['id'] try: results = prod.listRecomended() except (Exception) as err: error = True return handleError(err) finally: if not (error): return jsonify({'result': 'success', 'data': results})
def composer(temp_file_name): """ :param temp_file_name: path of a :class:`.tempfile` **.arb** that contains the information to generate a :class:`.Product` relative to the arborescense of a **.stp** file For every node of the :class:`.Product` the attribute **doc_file_path** indicates where is store the file **.stp** that represents the node """ output = open(temp_file_name.encode(), "r") product = Product.from_list(json.loads(output.read())) output.close() output = open(temp_file_name.encode(), "w+") # erase old data output.close() WS = XSControl_WorkSession() my_step_importer = StepImporter(product.doc_path) st = my_step_importer.shape_tool lr = TDF_LabelSequence() st.GetFreeShapes(lr) add_labels(product, lr.Value(1), st) writer = STEPCAFControl_Writer(WS.GetHandle(), False) for i in range(lr.Length()): writer.Transfer(lr.Value(i + 1), STEPControl_AsIs) writer.Write(temp_file_name)
def composer(temp_file_name): """ :param temp_file_name: path of a :class:`.tempfile` **.arb** that contains the information to generate a :class:`.Product` relative to the arborescense of a **.stp** file For every node of the :class:`.Product` the attribute **doc_file_path** indicates where is store the file **.stp** that represents the node """ output = open(temp_file_name.encode(),"r") product = Product.from_list(json.loads(output.read())) output.close() output = open(temp_file_name.encode(),"w+")# erase old data output.close() WS = XSControl_WorkSession() my_step_importer = StepImporter(product.doc_path) st = my_step_importer.shape_tool lr = TDF_LabelSequence() st.GetFreeShapes(lr) add_labels(product, lr.Value(1), st) writer = STEPCAFControl_Writer(WS.GetHandle(), False) for i in range(lr.Length()): writer.Transfer(lr.Value(i+1), STEPControl_AsIs) writer.Write(temp_file_name)
def get_product(id): """ Get specific product from the ProductData file """ f = open(PRODUCTDATA_FILENAME, "r") prod = Product() # default for row in f.readlines(): cols = row.split(",") # seperate line if int(cols[0]) == id: ''' create new procuct instance and assign values in construct ''' prod = Product(id=cols[0], name=cols[1], price=cols[2], quanity_in_stock=cols[3]) return prod
def searchProduct(dict1): name = input("Enter the name of the product: ") if name not in dict1.keys(): print("Product not found") else: values = dict1.get(name) product = Product(name, values[0], values[1]) print("The price is", product.price) print("The stock is", product.stock)
def dummy_compose(temp_file_name): output = open(temp_file_name.encode(),"r") product = Product.from_list(json.loads(output.read())) output.close() output = open(temp_file_name.encode(),"w+")# erase old data output.close() with open(temp_file_name, "w") as output: c = Composer(product, output) c.compose()
def addProduct(): error = False name = request.json['name'] dsc = request.json['dsc'] material = request.json['material'] genre = request.json['genre'] brand = request.json['brand'] type = request.json['type'] discount = request.json['discount'] price = request.json['price'] new = Product(name, dsc, material, genre, brand, type, discount, price) try: id = new.add() except (Exception) as err: error = True return handleError(err) finally: if not (error): return jsonify({'result': 'success', 'id': id})
def dummy_compose(temp_file_name): output = open(temp_file_name.encode(), "r") product = Product.from_list(json.loads(output.read())) output.close() output = open(temp_file_name.encode(), "w+") # erase old data output.close() with open(temp_file_name, "w") as output: c = Composer(product, output) c.compose()
def insertProduct(dict1): name = input("Enter the new name: ") while name in dict1.keys(): print("The product is already registered") name = input("Enter the new name: ") if len(dict1) == 10: print("Cannot add product, dictionary is full") else: price = float(input("Enter the new price: ")) stock = int(input("Enter the new stock: ")) product = Product(name, price, stock) dict1[name] = [product.price, product.stock]
def modifyProduct(admin): clear() print("--------------MODIFYING PRODUCT--------------") viewProducts(admin) print("Enter Product Id to be modified") previousid = raw_input() try: previousid = int(previousid) except Exception as e: print("Not valid product id") return None else: prod = setting.productsList.get(previousid, None) if not (prod): print("No product found with ID: " + str(previousid)) return None print("Want to modify id? (Enter new value or press enter)") id = raw_input() try: if id: id = int(id) else: id = previousid except Exception as e: print("Not valid product id") return None print("Want to modify product name? (Enter new value or press enter)") name = raw_input() name = name if name else prod.name print("Want to modify product Group? (Enter new value or press enter)") grp = raw_input() grp = grp if grp else prod.group print("Want to modify product SubGroup? (Enter new value or press enter)") sub = raw_input() sub = sub if sub else prod.subgroup print("Want to modify product Price? (Enter new value or press enter)") price = raw_input() if price: if isfloat(price): price = float(price) else: print("Not valid price value") return None else: price = prod.price return [Product(id, name, grp, sub, price), previousid]
def retrieve_products_for_interest(interest): list_url = "{}{}/{}-gifts{}".format(BASE_URL, LIST_URL, interest, QUERY_STR) html = retrieve_data("uncommon-goods.{}.html".format(interest), list_url) soup = bs(html, "html.parser") prod_links = [link["href"] for link in soup.select("article.product a")] for link in prod_links[:100]: prod_link = "{}{}".format(BASE_URL, link) fname = "{}.{}.html".format("uncommon-goods", link_to_fname(link)) print("Fetching {}...".format(prod_link)) html = retrieve_data(fname, prod_link) soup = bs(html, "html.parser") try: title = soup.find("h1", {"itemprop": "name"}).get_text() title = clean_whitespace(title) description = soup.select_one(".theStoryCopy p").get_text() description = clean_whitespace(description) image = soup.select_one("a#mainImage img")["src"] if not image.startswith("http"): image = "{}{}".format(BASE_URL, image) price = soup.find("span", {"itemprop": "price"}).get_text() price = float(clean_whitespace(price)) tags = get_tags(description) product = Product(title, "{}{}".format(BASE_URL, link), image, interest, tags, description, price=price) product.dump() except Exception as e: print("ERROR:", e) print("")
def retrieve(): list_link = "{}{}".format(BASE_URL, FILM_LIST) html = retrieve_data("imdb.top-films.html", list_link) soup = bs(html, "html.parser") film_links = soup.select("tbody.lister-list tr .titleColumn a") film_links = [link["href"] for link in film_links] for link in film_links[:100]: film_link = "{}{}".format(BASE_URL, link) fname = "{}.{}.html".format("imdb", link_to_fname(link)) print("Fetching {}...".format(film_link)) html = retrieve_data(fname, film_link) soup = bs(html, "html.parser") try: title = soup.select_one(".title_wrapper h1").get_text() title = clean_whitespace(title) description = soup.select_one(".plot_summary .summary_text") description = clean_whitespace(description.get_text()) image = soup.select_one(".poster a img")["src"] if not image.startswith("http"): image = "{}{}".format(BASE_URL, image) link = soup.select_one(".winner-option.watch-option")["data-href"] genres = soup.select(".title_wrapper .subtext a[href^=\"/genre\"]") genres = [clean_whitespace(genre.get_text()) for genre in genres] product = Product(title, "{}{}".format(BASE_URL, link), image, "films", genres, description) product.dump() except Exception as e: print("ERROR:", e) print("")
def decompose(path, temp_file_name): """ Decomposes a STEP file into several STEP files (one per unique assembly/part) :param path: Path of a file **.stp** :param temp_file_name: path of a :class:`.tempfile` **.arb** that contains the data required to generate a :class:`.Product` relative to the arborescense of a **.stp** file """ output = open(temp_file_name.encode(),"r") old_product = Product.from_list(json.loads(output.read())) step_importer = StepImporter(path) shape_tool = step_importer.shape_tool product = step_importer.generate_product_arbre() decompose_children(product, old_product, shape_tool) write_step(product, old_product, shape_tool)
def decompose(path, temp_file_name): """ Decomposes a STEP file into several STEP files (one per unique assembly/part) :param path: Path of a file **.stp** :param temp_file_name: path of a :class:`.tempfile` **.arb** that contains the data required to generate a :class:`.Product` relative to the arborescense of a **.stp** file """ output = open(temp_file_name.encode(), "r") old_product = Product.from_list(json.loads(output.read())) step_importer = StepImporter(path) shape_tool = step_importer.shape_tool product = step_importer.generate_product_arbre() decompose_children(product, old_product, shape_tool) write_step(product, old_product, shape_tool)
def get_all_products(): """ Get all products from the ProductData file """ ''' open file for reading ''' f = open(PRODUCTDATA_FILENAME, "r") productList = [] for row in f.readlines(): cols = row.split(",") # seperate line ''' create new procuct instance and assign values in construct ''' prod = Product(id=cols[0], name=cols[1], price=cols[2], quanity_in_stock=cols[3]) ''' add to product to list ''' productList.append(prod) return productList
def createBatch(): batch_name = str(input("\nEnter a name for your batch: ")) product = Product(str(input("\nWhat product is in the batch?: "))) palletCount = int( input("How many pallets in the batch? Integer only: ")) caseCount = int( input("How many cases per pallet? Integer only: ")) itemCount = int( input("How many items per case? Integer only: ")) # recursive list comprehension builds a linked list of linked lists... this is our asset hierarchy batch = Asset(product, "batch", [Asset(product, "pallet", [Asset(product, "case", [Asset(product, "item", None, tag=f"{product}-{pallet+1}-{case+1}-{item+1}") for item in range(itemCount)], tag=f"{product}-{pallet+1}-{case+1}") for case in range(caseCount)], tag=f"{product}-{pallet + 1}") for pallet in range(palletCount)], tag=batch_name) return batch
def ProductSetActive(): error = False new = Product() new.id = request.json['id'] new.active = request.json['active'] try: new.setActive() except (Exception) as err: error = True return handleError(err) finally: if not (error): return jsonify({'result': 'success'})
def addProduct(admin): clear() print("---------ADD PRODUCT---------") # viewProducts(admin) print("Enter Product Id") id = raw_input() print("Enter Product Name") name = raw_input() print("Enter Product Group") grp = raw_input() print("Enter Product SubGroup") sub = raw_input() print("Enter Product Price") price = raw_input() if not (id.isdigit() and isfloat(price) and name and grp and sub): print( "please enter valid information (all are mandatory and id should be integer)" ) return None return Product(int(id), name, grp, sub, float(price))
def generate_product_arbre(self): """ Generates a :class:`.Product` relative to the assemblies of the file **.stp**, for every node of the :class:`.Product` it includes a label (:class:`.OCC.TDF.TDF_Label`) that represents and identifies the node , openPLM can only work whit a single root **.stp** files """ roots = TDF_LabelSequence() self.shape_tool.GetFreeShapes(roots) if roots.Length() != 1: raise MultiRootError deep = 0 product_id = [1] root = roots.Value(1) name = get_label_name(root) self.main_product = Product(name, deep, root, self.id, product_id[0], self.file) product_id[0] += 1 expand_product(self.shape_tool, self.main_product, self.shapes_simples, deep + 1, self.id, self.main_product, product_id, self.file) return self.main_product
return np.loadtxt(filename) if __name__ == "__main__": insp1_time = dat_parser("data_files/servinsp1.dat") insp22_time = dat_parser("data_files/servinsp22.dat") insp23_time = dat_parser("data_files/servinsp23.dat") ws1_time = dat_parser("data_files/ws1.dat") ws2_time = dat_parser("data_files/ws2.dat") ws3_time = dat_parser("data_files/ws3.dat") env = simpy.Environment() component1 = Component("Component 1") component2 = Component("Component 2") component3 = Component("Component 3") product1 = Product("Product 1", [component1]) product2 = Product("Product 2", [component1, component2]) product3 = Product("Product 3", [component1, component3]) workstation1 = Workstation(env, "Workstation 1", product1, ws1_time) workstation2 = Workstation(env, "Workstation 2", product2, ws2_time) workstation3 = Workstation(env, "Workstation 3", product3, ws3_time) inspector1 = Inspector(env, "Inspector 1", [component1], [insp1_time], [workstation1, workstation2, workstation3]) inspector2 = Inspector(env, "Inspector 2", [component2, component3], [insp22_time, insp23_time], [workstation2, workstation3])
from classes import Product, Review from mapping import PRODUCT_ID, PRODUCT_PARENT, PRODUCT_TITLE, \ PRODUCT_CATEGORY, REVIEW_DATE, REVIEW_ID, REVIEW_CUSTOMER, \ REVIEW_STARS, REVIEW_HEADLINE, REVIEW_BODY # using the read only method since you're not gonna be editing the spreadsheet wb = load_workbook(filename="reviews-sample.xlsx", read_only=True) sh = wb.active products = [] reviews = [] # Using the values_only beacuse you just return the cell value for row in sh.iter_rows(min_row=2, values_only=True): product = Product(id=row[PRODUCT_ID], parent=row[PRODUCT_PARENT], title=row[PRODUCT_TITLE], category=row[PRODUCT_CATEGORY]) products.append(product) # You need to parse the date from the spreadsheet into datetime format spread_date = row[REVIEW_DATE] parsed_date = datetime.strptime(spread_date, "%Y-%m-%d") review = Review(id=row[REVIEW_ID], customer_id=row[REVIEW_CUSTOMER], stars=row[REVIEW_STARS], headline=row[REVIEW_HEADLINE], body=row[REVIEW_BODY], date=parsed_date) reviews.append(review)
def _create_product(self, name, picture): product = Product(self.frame, name=name, picture=picture) self._products[name] = product product.pack_propagate(0) return product
def planning(df, start_date, end_date, batchID): """ :param df: The dataframe containing the input :param start_date: The date that the planning starts :param end_date: The date the planning ends (exclusive, so before) :param batchID: :return: Makes the planning of the input """ """ Initiate tracking the data, give a priority to the orders, and get all availible work centers """ track = TrackingData() # Makes an object to track data about the planning df_zcs = zcs() # Obtain the dataframe containing info about the materials and the work centers they can be made on track.orders_planned = len(df['Order']) # Track the amount of orders that has to be planned df['Estimated time'] = pd.to_datetime(df['Estimated time'], unit='s') # Makes the estimated duration to produce a product a datetime object df['needed on'] = pd.to_datetime(df['needed on'], infer_datetime_format=True) # Sets the needed on date to datetime df, wrong = prioritiseOrdersDefault(df, df_zcs, start_date, end_date, batchID) # Wrong is the list of orders that couldn't be planned (not enough information) machines = MachineDf(start_date, track) # Makes a dictionary containing all available machines """ Get the dictionaries to plan the order and then create the objects for the order and put those in the dicts """ n_on = df['needed on'] orig_document = df['Originating document'] material_number = df['Material'] work_center = df['Work center'] order = df['Order'] in_production = df['Start Point'] mould_df = df['Mould'] quantity = df['Rec./reqd quantity'] prio = df['Priority'] est_time = df['Estimated time'] desc = df['Material Description'] not_planned = [] # A list containing the orders that couldn't be planned and the reason why products = {} # Dict of orders to assign to machines in_machine = {} # Dict of orders already being processed in machines dummy_amount = 0 for i in range(len(order)): # Making a dummy order if str(material_number[i]) == 'nan' or str( material_number[i]) == 'None': # THe order has no material number --> dummy product dummy_amount += 1 machine = [str(work_center[i]).replace('.0', '')] # Get the work center from the input pt = getMouldMachineTime(quantity[i], str(mould_df[i]), machine[0], df_zcs['Mould', 'Mean zcs'].sort_values('Mould')) # The time it takes to make the order if not pt: # The duration to make the order can't be estimated not_planned.append( [str(material_number[i]), "Dummy doesn't have enough information to calculate the duration", str(order[i])]) else: insert = AddInsert(str(order[i]), df[['Order', 'Insert 1 (mould)', 'Insert 2 (mould)', 'Insert 3 (mould)', 'Insert 4 (mould)', 'Insert 5 (mould)']]) # Get the list of inserts from the input product = Product(str(order[i]), str(orig_document[i]), "Dummy" + str(dummy_amount), pt, "dummy product", quantity[i], str(mould_df[i]), insert, machine, n_on[i], in_production[i], prio[i]) # Make the object for the order if in_production[i] == 1: # The order is already being produced on a work center in_machine[product.moulds] = product else: # The order is added to the list of orders that need to be planned if product.moulds in in_machine.keys() and n_on[i] <= end_date: # IF the mould is already used on a machine combineOrder(in_machine[product.moulds], product) elif product.moulds in products.keys(): # If the mould is already in the dict to be planned, they are combined combineOrder(products[product.moulds], product) else: # If the product hasn't been ordered before products[product.moulds] = product # Add the product to the list # Making an order that is already being produced elif in_production[i] == 1 and type(est_time[i].hour) == int: machine = str(work_center[i]).replace('.0', '') # Get the work center from the input if str(machine) == 'nan': not_planned.append( [str(material_number[i]), 'No work center for a product that is already in production', str(order[i])]) else: insert = AddInsert(str(order[i]), df[['Order', 'Insert 1 (mould)', 'Insert 2 (mould)', 'Insert 3 (mould)', 'Insert 4 (mould)', 'Insert 5 (mould)']]) # Get the inserts from the input product = Product(str(order[i]), str(orig_document[i]), str(material_number[i]), est_time[i], str(desc[i]), quantity[i], str(mould_df[i]), insert, machine, n_on[i], in_production[i], prio[i]) in_machine[ product.moulds] = product # The order is added to the list of orders that are already being produced on a work center # Making a normal order elif type(est_time[i].hour) == int: machine = addAndSortMachines(df_zcs, str(material_number[i])) # Get a sorted list containing the work centers insert = AddInsert(str(order[i]), df[ ['Order', 'Insert 1 (mould)', 'Insert 2 (mould)', 'Insert 3 (mould)', 'Insert 4 (mould)', 'Insert 5 (mould)']]) # Get the inserts from the input product = Product(str(order[i]), str(orig_document[i]), str(material_number[i]), est_time[i], str(desc[i]), quantity[i], str(mould_df[i]), insert, machine, n_on[i], in_production[i], prio[i]) if product.moulds in in_machine.keys() and n_on[i] <= end_date: # IF the mould is already used on a machine combineOrder(in_machine[product.moulds], product) elif product.moulds in products.keys(): # If the mould is already in the dict to be planned, they are combined combineOrder(products[product.moulds], product) else: # If the product hasn't been ordered before products[product.moulds] = product # Add the product to the list else: # If the duration isn't a datetime object not_planned.append([str(material_number[i]), 'No time available', str(order[i])]) """ Dynamically get the mould change capacity """ mould_changes = [] # The list containing all the mould changes change_capacity = mouldChangeCapacity(start_date, end_date) """ Plan the orders that are already being produced first """ for order in in_machine: # For each order that is already being produced if in_machine[order].machines != 'nan' and in_machine[order].machines != 'None': # The order has a work center machines[in_machine[order].machines].first(in_machine[order]) # Plan the order on the work center """ Add the rest of the orders to the work centers, so they can be planned """ half_time = get_half_time(end_date, start_date) # Calculate when half the time has passed for product in products: # Plan the products in the work centers if products[product].machines != '[]' and products[product].machines != 'nan': # The order has work centers to plan on emptiest = [] # Keeps track of the work center with the least time planned yet emptiest_in_time = [] # Keeps track of the work center with the least time, where the order can be planned in time for j in products[product].machines: # Try each possible work center if j in machines.keys(): # If the work center is available if not products[product].scheduled and machines[ j].remainder <= end_date: # If the order isn't planned yet and there is still time on the work center if products[product].finish_date < end_date and withinTime(machines[j].remainder,products[product].time, end_date): if half_time >= machines[j].remainder: machines[j].add(products[product]) # Add to order to be scheduled in the work center elif (emptiest_in_time == [] or emptiest_in_time[1] > machines[j].remainder) and withinTime(machines[j].remainder, products[product].time, products[product].finish_date): # maybe change so it looks at a later needed on date, instead of the first of the combined orders emptiest_in_time = [machines[j], machines[j].remainder] if (emptiest == [] or emptiest[1] > machines[j].remainder) and machines[j].remainder < end_date: emptiest = [machines[j], machines[j].remainder] # The order couldn't be scheduled in time, but this is the best possible work center untill now """ The orders that could not be added to a work center yet will be added to emptiest work center, if possible """ if not products[product].scheduled: # If the order hasn't been scheduled yet if emptiest_in_time: emptiest_in_time[0].add(products[product]) elif emptiest: # If there was a work center where (part of) the order could be scheduled before the end date is reached emptiest[0].add(products[product]) else: # There was no possibility to schedule the order not_planned.append([products[product].id, "No available work center in time", products[product].order]) for p in products[product].combined: not_planned.append([p.id, "No available work center in time", p.order]) else: # There was no work center to schedule the order on not_planned.append([products[product].id, "No work center for this item", products[product].order]) for p in products[product].combined: not_planned.append([p.id, "No work center for this item", p.order]) """ The orders that are added to the work centers are first ordered and then scheduled """ for m in machines: # For each possible work center if len(machines[m].products) > 0: # There is an order to plan machines[m].sortProducts(mould_changes, track, change_capacity, not_planned, end_date) # Sorts the orders and plans them """ Information for tracking the orders is added After this the schedule, mould changes, and not scheduled orders are written to the output """ addMachineTrackingInfo(machines, start_date, end_date, track) # Makes the tracking information for how much the work centers are used printSchedule(machines, end_date, track, batchID) printMould(mould_changes, track) printNotScheduled(not_planned, wrong, track, batchID) trackDataFrame(track, batchID)
def home_page(): prod = Product() all_products = prod.get_all_products() return render_template("index.html", all_products=all_products)
# import the classes module from classes import Product, Inventory # define your products apple = Product('Apple', 10, price=.44) banana = Product('Banana', 13, 3, 1.00) lettuce = Product('Lettuce', 100, 8, 1.44) # create an inventory of the products with a store name and ID myinv = Inventory('Boone', 51439) myinv.addProduct(apple) myinv.addProduct(banana) myinv.addProduct(lettuce) # Creating a neat table to display the contents of the inventory def storeTable(): print('-' * 45) print(f"Store name: {myinv}\nStore code: {myinv.store_code}") print('-' * 45) print("\nProducts available:\n") print("\tName\tID\tQuantity\tPrice\n") for item in myinv.product_list: print( f"{item.name : >12}{item.id : >6}{item.quantity : >14}{item.price : >13}" ) print('-' * 45) print(f"\nNet Value:{myinv.value() : >35}") print("Before deleting:\n")
import json from classes import Product from constants import PRODUCT_PATH if __name__ == "__main__": for product_fname in PRODUCT_PATH.iterdir(): fpath = PRODUCT_PATH.joinpath(product_fname) print("Cleaning {}".format(fpath)) with open(fpath) as f: data = json.load(f) price = data["price"] del data["price"] product = Product(*list(data.values()), price=price or 10) product.dump()
def modProduct(): error = False prod = Product() prod.id = request.json['id'] prod.name = request.json['name'] prod.dsc = request.json['dsc'] prod.material = request.json['material'] prod.genre = request.json['genre'] prod.brand = request.json['brand'] prod.type = request.json['type'] prod.discount = request.json['discount'] prod.price = request.json['price'] try: prod.mod() except (Exception) as err: error = True return handleError(err) finally: if not (error): return jsonify({'result': 'success'})