def cart_update(): for id_, qty in request.args.items(): # this makes sure we only use ints # noinspection PyBroadException try: qty = int(qty) inv_item = db.get_inventory_item(InventoryItem(id_)) if inv_item.quantity >= qty: db.update_cart(user=User(current_user.get_id()), item=ShoppingCartItem(item=inv_item), qty=qty) else: flask.flash( "<b>Exceeds stock:</b> {} has no more than {} items available." .format(inv_item.name, inv_item.quantity), "warning") except Exception: continue return redirect('/cart')
def handle_headers(payload, sock): block_headers = Headers.parse(payload) print(f'{len(block_headers.headers)} new headers') update_blocks(block_headers) # after 500 headers, get the blocks if len(blocks) < 500: send_getheaders(sock) else: items = [ InventoryItem(2, int_to_little_endian(hash_, 32)) for hash_ in blocks[:10] ] getdata = GetData(items=items) msg = Message(getdata.command, getdata.serialize()) sock.send(msg.serialize()) print(f'We now have {len(blocks)} headers')
def get_inventory_item(item, db=None): """ Gets a singular InventoryItem :param item: InventoryItem :param db: optional :return: InventoryItem """ db = db or get_db() cur = db.cursor() cur.execute(""" SELECT ItemID, ItemName, Description, Price, Category, Quantity FROM InventoryItem WHERE ItemID=? """, [item.id_]) row = cur.fetchone() if row is not None: return InventoryItem(id_=row[0], name=row[1], description=row[2], price=row[3], category=ItemCategory[row[4]], qty=row[5]) return None
def get_purchase(purchase, db=None): """ Gets a purchase from the database based on PurchaseID :param purchase: Purchase, must have id :param db: optional, the database connection """ db = db or get_db() cur = db.cursor() cur.execute(""" SELECT Username, TotalPrice, CreditCard, Address FROM Purchase WHERE PurchaseID = ? """, [purchase.id_]) row = cur.fetchone() try: purchase = Purchase(id_=purchase.id_, username=row[0], total_price=row[1], credit_card=row[2], address=Address().from_str(row[3])) except Exception as e: print("invalid purchase:", e) cur.execute(""" SELECT InventoryItemID, Price, Quantity FROM PurchaseItem WHERE pi.PurchaseID = ? """, [purchase.id_]) for row in cur.fetchall(): try: item = get_inventory_item(InventoryItem(id_=row[0]), db) purchase.items.append(ShoppingCartItem(item=item, price=row[1], qty=row[2])) except Exception as e: print("invalid purchase item:", e) cur.close() return purchase
def create_model(self, form): # only if its set do we care if its unique if form.identifier.data and InventoryItem.objects( identifier=form.identifier.data).count(): flash('Identifier (%s) is already in use' % form.identifier.data) return False # overriden to update the date values of the model now = datetime.now() item = InventoryItem( name=form.name.data, identifier=form.identifier.data, comment=form.comment.data, status=form.status.data, # get the model for the target group group=InventoryGroup.objects.get(id=form.group.data), date_added=now, date_updated=now) try: item.save() except Exception, e: flash('Unable to add the item', category='error') if settings.DEBUG: flash('DEBUG: %s' % e, category='error') return False
def create_db(force=False): """ Automatically creates database, if needed. :param force: if True, creates the database anyways. NOTE: does not delete existing db. Renames renames old database to DATABASE_FILE.db.old. """ if force: try: print("attempting to archive existing database.") os.rename(DATABASE, DATABASE + ".old") except OSError as ose: print("error archiving database file:", ose) # if database does not exist, create tables if not os.path.exists(DATABASE) or force: db = sqlite3.connect("./data.db") cur = db.cursor() # create User table cur.execute(""" CREATE TABLE User ( UserID INTEGER PRIMARY KEY AUTOINCREMENT, Username TEXT, Password TEXT ); """) # create InventoryItem table cur.execute(""" CREATE TABLE InventoryItem ( ItemID INTEGER PRIMARY KEY AUTOINCREMENT, ItemName TEXT, Description TEXT, Price FLOAT, Category TEXT, Quantity INTEGER ); """) db.commit() # create Purchase table cur.execute(""" CREATE TABLE Purchase ( PurchaseID INTEGER PRIMARY KEY AUTOINCREMENT, Username TEXT, TotalPrice FLOAT, CreditCard TEXT, Address TEXT ); """) db.commit() # create PurchaseItem table cur.execute(""" CREATE TABLE PurchaseItem ( PurchaseID INTEGER, InventoryItemID INTEGER, Price FLOAT, Quantity INTEGER, FOREIGN KEY (PurchaseID) REFERENCES Purchase (PurchaseID), FOREIGN KEY (InventoryItemID) REFERENCES InventoryItem (ItemID) ); """) db.commit() # create ShoppingCartItem table cur.execute(""" CREATE TABLE ShoppingCartItem ( UserID INTEGER, InventoryItemID INTEGER, Price FLOAT, Quantity INTEGER, FOREIGN KEY (UserID) REFERENCES User (UserID), FOREIGN KEY (InventoryItemID) REFERENCES InventoryItem (ItemID) ); """) db.commit() # insert Admin user add_user(User(username="******", password="******"), db) # insert Sample Inventory items add_item(InventoryItem(name="Apple", description="One a day is 19g of sugar!", price=1.25, category=ItemCategory.TOYS, qty=23), db) add_item(InventoryItem(name="Teddy Bear", description="Missing his head, but he still loves you!", price=9.99, category=ItemCategory.TOYS, qty=6), db) add_item(InventoryItem(name="Book", description="That's a nice cover. I might read that.", price=42.11, category=ItemCategory.BOOKS, qty=2), db) add_item(InventoryItem(name="The Great Gatsby", description="Every girls dream love story.", price=18.50, category=ItemCategory.BOOKS, qty=30), db) add_item(InventoryItem(name="Twilight", description="Spurkle Purty", price=0.99, category=ItemCategory.BOOKS, qty=88), db) add_item(InventoryItem(name="Raspberry Pi", description="What do you do with this?", price=3.14, category=ItemCategory.SMALL_ELECTRONICS, qty=99), db) add_item(InventoryItem(name="Apple Pi", description="Raspberry pi, but tastier!", price=5.55, category=ItemCategory.SMALL_ELECTRONICS, qty=99), db) add_item(InventoryItem(name="Toothpaste", description="Minty Fresh", price=500.99, category=ItemCategory.HOUSEHOLD_ITEMS, qty=10), db) db.commit() cur.close() db.close()
def inventory_submit(request): if request.method != 'POST': return HttpResponseNotFound('No POST data sent') # list of bundleids to ignore bundleid_ignorelist = ['com.apple.print.PrinterProxy'] submission = request.POST serial = submission.get('serial').upper() machine = None if serial: try: machine = Machine.objects.get(serial=serial) except Machine.DoesNotExist: return HttpResponseNotFound('Serial Number not found') compression_type = 'base64bz2' if 'base64bz2inventory' in submission: compressed_inventory = submission.get('base64bz2inventory') elif 'base64inventory' in submission: compressed_inventory = submission.get('base64inventory') compression_type = 'base64' if compressed_inventory: compressed_inventory = compressed_inventory.replace(" ", "+") inventory_str = utils.decode_to_string(compressed_inventory, compression_type) try: inventory_list = plistlib.readPlistFromString(inventory_str) except Exception: inventory_list = None if inventory_list: try: inventory_meta = Inventory.objects.get(machine=machine) except Inventory.DoesNotExist: inventory_meta = Inventory(machine=machine) inventory_meta.sha256hash = \ hashlib.sha256(inventory_str).hexdigest() # clear existing inventoryitems machine.inventoryitem_set.all().delete() # insert current inventory items inventory_items_to_be_created = [] for item in inventory_list: app, _ = Application.objects.get_or_create( bundleid=item.get("bundleid", ""), name=item.get("name", ""), bundlename=item.get("CFBundleName", "")) # skip items in bundleid_ignorelist. if not item.get('bundleid') in bundleid_ignorelist: i_item = InventoryItem(application=app, version=item.get("version", ""), path=item.get('path', ''), machine=machine) if is_postgres(): inventory_items_to_be_created.append(i_item) else: i_item.save() machine.last_inventory_update = timezone.now() inventory_meta.save() if is_postgres(): InventoryItem.objects.bulk_create( inventory_items_to_be_created) machine.save() return HttpResponse("Inventory submmitted for %s.\n" % submission.get('serial')) return HttpResponse("No inventory submitted.\n")
def add_item(btn): session.merge(InventoryItem(character=character.name, item=btn.text)) session.commit() self.dismiss() item_tab.set_items()