def create_or_retrieve(self, request=None, objdescription="test", format=None): if request.method == 'GET': try: found_desc = Inventory.objects.get(description=objdescription) data = {"description": objdescription, "id": found_desc.id} return HttpResponse(json.dumps(data), status=200) except ObjectDoesNotExist as e: return HttpResponse(json.dumps({"status": "NoSuchID"}), status=404) elif request.method == "POST": try: found_description = Inventory.objects.get( description=objdescription) return HttpResponse(json.dumps({"status": "AlreadyExists"}), status=403) except ObjectDoesNotExist as e: pass u = Inventory(description=objdescription) u.save() return HttpResponse(json.dumps({"status": "SuccessSetDescription"}))
def create_inventory_record(p): new_inventory = Inventory(sfmId=p.sfmId, style=p.style, size=p.size, color=p.color, inStock=0, arrivalDate=date.today(), minimum=0, maximum=100) new_inventory.save()
def add_inventory_row(parent, entries): validators = ViconfValidators() fieldset = parent.ordered_fields for field, value in entries.items(): if field not in fieldset: raise ValidationError("{} not defined in parent".format(field)) else: validator = fieldset[field] if not validators.validate(validator, value): raise ValidationError( validators.VALIDATORS[validator]['error']) inventory = Inventory(parent=parent, fields=entries) inventory.save() return inventory
def _initialize_elements(self): restaurant = Restaurant() restaurant.save() inventory = Inventory() inventory.restaurant = restaurant inventory.save() element = OrderElement() element.order_id = self.order.id element.final_price = 5 element.offer_number_in_order = 0 element.price = 5 element.inventory = inventory element.save() return [ element, ]
def add_inventory(**kwargs): name = kwargs.get('name', None) fields = kwargs.get('fields', None) if name is None: raise ValidationError("name must be set") if fields is None: raise ValidationError("fields must be set") entries = {'name': name, 'fields': fields} inventory = Inventory() inventory.fields = entries inventory.save() return inventory
def get(self, request, **kwargs): show_all_inventories = request.GET.get('show_all', '') user = request.user list_of_inventories = [] status = HTTP_200_OK try: inventory_user = InventoryUser.user_exists(username=user.username) user_permitted = Inventory.is_user_permitted(user=inventory_user) if show_all_inventories == "true": users_inventories = Inventory.objects.filter( ~Q(store_manager=inventory_user) & ~Q(dept_managers_subscribed=inventory_user)) for inventory in users_inventories: inventory_dict = { 'name': inventory.inventory_name, 'store_manager': inventory.store_manager.user.username } list_of_inventories.append(inventory_dict) elif inventory_user.is_store_mgr or user_permitted: users_inventories = Inventory.get_all_inventories( user=inventory_user) for inventory in users_inventories: inventory_dict = {} inventory_records = InventoryRecords.get_inventory_records_data( inventory=inventory) inventory_dict['name'] = inventory.inventory_name inventory_dict['records'] = inventory_records inventory_dict[ 'store_manager'] = inventory.store_manager.user.username list_of_inventories.append(inventory_dict) except Exception as e: status = HTTP_400_BAD_REQUEST list_of_inventories.append({'error': "Can't fetch all records"}) return HttpResponse(json.dumps( {'inventories_list': list_of_inventories}), status=status, content_type='application/json')
def create_or_retrieve(self, request=None, uname="test", description="test", format=None): page = urllib.request.urlopen('http://localhost:8000/user/' + uname) json_string = page.read() parsed_json = json.loads(json_string) if request.method == "GET": try: found_id = parsed_json['id'] user_id = Inventory.objects.get(id=found_id) except ObjectDoesNotExist as e: return HttpResponse(json.dumps({"status": "NoSuchID"}), status=404) data = {"ID": user_id.id, "Inventory": user_id.description} return HttpResponse(json.dumps(data)) elif request.method == "POST": try: found_id = parsed_json['id'] user_id = Inventory.objects.get(id=found_id) return HttpResponse(json.dumps({"status": "AlreadyExists"}), status=403) except ObjectDoesNotExist as e: pass u = Inventory(id=found_id) u.save() return HttpResponse(json.dumps({"status": "Success"})) elif request.method == "PUT": try: found_id = parsed_json['id'] user = Inventory.objects.get(id=found_id) user.description = description user.save() return HttpResponse(json.dumps({"status": "Success"})) except ObjectDoesNotExist as e: return HttpResponse(json.dumps({"status": "NoSuchUser"}))
def _initialize_inventory(self, user_id): restaurant = Restaurant() restaurant.save() staff_member = StaffMember() staff_member.restaurant = restaurant staff_member.save() inventory = Inventory() inventory.restaurant = restaurant inventory.product = 'default product' inventory.price = 5 inventory.save() return inventory
def post(self, request): user = request.user request_data = json.loads(request.body) subscribe_to = request_data.get('subscribe_to') inventory_name = request_data.get('inventory_name') # store_manager = request_data.get('store_manager') inventory_user = InventoryUser.user_exists(username=user.username) status = HTTP_200_OK response = [] try: if subscribe_to: inventory = Inventory.objects.filter( inventory_name=subscribe_to).first() if (not inventory_user.is_store_manager_for_inventory( subscribe_to) and not inventory_user in inventory.dept_managers_subscribed.all()): inventory.dept_managers_subscribed.add(inventory_user) response.append({'success': True}) else: if not inventory_user.is_store_mgr: inventory_user.is_store_mgr = True inventory_user.save() inventory_new = Inventory(inventory_name=inventory_name, store_manager=inventory_user) inventory_new.save() response.append({'success': True}) except Exception as e: status = HTTP_400_BAD_REQUEST response.append({'error': 'Inventory does not exist'}) return HttpResponse(json.dumps(response), status=status, content_type='application/json')
def generate_items(): from inventory.models import Inventory items_to_create = [] # find alternative to this thanks to itertool for i, item in enumerate(ITEMS): for j in range(60): item_to_create = {} item_to_create['product_name'] = item item_to_create['product_id'] = i item_to_create['date'] = date.today() + timedelta(days=-j) item_to_create['inventory_level'] = randint(0, 30) items_to_create.append(Inventory(**item_to_create)) print(len(items_to_create)) Inventory.objects.bulk_create(items_to_create)
def init_db(): # Set up test data for now from inventory.models import Item, Inventory, ItemInventoryMap print("Iniatlizing Database") Base.metadata.drop_all(bind=engine) Base.metadata.create_all(bind=engine) dagger = Item(name='dagger') db_session.add(dagger) rapier = Item(name='rapier') db_session.add(rapier) db_session.commit() group_inventory = Inventory(name="Group") has_5_daggers = ItemInventoryMap(item=dagger, quantity=5) group_inventory.items.append(has_5_daggers) db_session.add(group_inventory) db_session.commit()
def _initialize_method_from_storage(self): order = Order() order.created_at = datetime.datetime(2020, 1, 27, 0, 0, 0, 1) order.save() restaurant = Restaurant() restaurant.save() staffmember = StaffMember() staffmember.restaurant = restaurant staffmember.save() inventory = Inventory() inventory.in_store = 10 inventory.product = 'mocked_product' inventory.restaurant = restaurant inventory.save() element = OrderElement() element.price = 5.31 element.inventory = inventory element.product = 'mocked_product' element.order = order element.final_price = 5.31 element.offer_number_in_order = 0 element.save() order.elements = [ element, ] element = OrderElement() element.price = 2.11 element.final_price = 2.11 element.offer_number_in_order = 0 element.order = order element.product = 'mocked_product' element.inventory = inventory element.save() order.elements.append(element) order.save() return order, staffmember
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['inventory_list'] = Inventory.get_by_name_color_pairs() return context
def save_inventory(self, form, product): inventory_qty = form.cleaned_data['inventory_qty'] Inventory.create_inventory(product, inventory_qty)
def inventory_query(self, ItemId, country, crontab=False): try: count = 0 while count < 5: try: count += 1 amazon = amazon_api(country) product = amazon.lookup(ItemId=ItemId) break except AsinNotFound: product = None except: time.sleep(0.1 + random.random() * 0.3) continue if crontab: inventory = Inventory.objects.filter(asin=ItemId, country=country)[0] if not product: inventory_time = Inventory_time(asin=inventory, inventory=0, sale_quan=0, bsr_rank=0, date=datetime.datetime.now(), price=0, sale_amount=0, star='ASIN已经下架') inventory_time.save() return "No_Asin" else: if not product: inventory = Inventory(title="No_Asin", asin=ItemId, country=country, inventory=0) inventory.save() return "No_Asin" else: print(product.title) inventory = Inventory(title=product.title, asin=ItemId, country=country) inventory.save() item = { 'offer_id': product._safe_get_element( 'Offers.Offer.OfferListing.OfferListingId'), 'quantity': 999 } print('cart_create') count = 0 while count < 5: try: count += 1 product = amazon.lookup(ItemId=ItemId) cart = amazon.cart_create({ 'offer_id': product.offer_id, 'quantity': 1 }) break except: time.sleep(0.1 + random.random() * 0.3) continue print('cart_clear') count = 0 while count < 5: try: count += 1 amazon.cart_clear(cart.cart_id, cart.hmac) break except: time.sleep(0.1 + random.random() * 0.3) continue print('cart_add') count = 0 while count < 5: try: count += 1 new_cart = amazon.cart_add(item, cart.cart_id, cart.hmac) break except: time.sleep(0.1 + random.random() * 0.3) continue try: for item in new_cart: cart_item_id = item.cart_item_id quantity = new_cart[cart_item_id].quantity except: if crontab and Inventory_time.objects.filter(asin=inventory)[1]: quantity = Inventory_time.objects.filter( asin=inventory)[0].inventory else: quantity = 0 #reviews_page=s.get(product.reviews[1],proxies=pro_chi()) #if reviews_page.status_code != 200: # print(reviews_page.status_code) # raise Exception #else: #try: #reviews=int(re.sub(',','',Selector(text=reviews_page.content).xpath('/html/body/div[1]/div[2]/div[2]/div[1]/b').extract()[0].split(" ")[0][3:])) #except: #reviews=0 #reviews_add=0 #if crontab: # reviews_add=reviews-Inventory_time.objects.filter(asin=inventory).first().reviews bsr_rank = product.sales_rank price = product.price_and_currency[0] price_unit = product.price_and_currency[1] sale_amount, sale_quan = 0, 0 if inventory.inventory: sale_quan = inventory.inventory - int(quantity) if price: sale_amount = price * sale_quan else: sale_amount, price = 0, 0 if sale_quan < 0: sale_amount, sale_quan = 0, 0 inventory_time = Inventory_time(asin=inventory, inventory=quantity, sale_quan=sale_quan, bsr_rank=bsr_rank, date=datetime.datetime.now(), price=price, sale_amount=sale_amount) inventory_time.save() inventory.inventory = quantity #if not crontab: inventory.img_url = product.medium_image_url inventory.detail_page_url = product.detail_page_url inventory.category = product.product_group inventory.price_unit = price_unit inventory.save() get_reviews.delay(country, inventory.asin, crontab) #except: # inventory.inventory = 0 # inventory.save() except CartException: logger.info("ASIN商品不存在") except SoftTimeLimitExceeded: logger.info("Soft Time Limit Exceeded") except Exception as e: if crontab: dt = datetime.datetime.now( pytz.utc) + datetime.timedelta(seconds=20) self.retry(eta=dt, exc=e, max_retries=1)
def form_valid(self, form): item = form.save(commit=False) item.save() new_inventory_item = Inventory(item=item) new_inventory_item.save() return super(InventoryAddItem, self).form_valid(form)
def test_populate_models(self): Inventory.populate() self.assertTrue(Inventory.objects.count(), 2)
def appenddb(request): test1 = Inventory(name='www.amazon.com') test1.save() return HttpResponse("<p>The record be appended!</p>")
def add_inventory(request): """ Adds a piece of inventory. """ LocationFormSet = modelformset_factory(LocationAmount, fields = ('location', 'amount'), extra=3, formset=RequiredFormSet) KeywordFormSet = modelformset_factory(KeywordValue, fields = ('keyword', 'value'), extra = Keyword.objects.count()) if request.method == 'POST': inventory_form = InventoryForm(request.POST, prefix="inv") location_formset = LocationFormSet(request.POST, prefix = "loc") kw_formset = KeywordFormSet(request.POST, prefix="kw") if inventory_form.is_valid() and location_formset.is_valid() \ and kw_formset.is_valid(): # Is there an easier way to do this with an Inventory ModelForm? part_str = inventory_form.cleaned_data['part'] color = inventory_form.cleaned_data['color'] part = Part.objects.get(part_id__iexact=part_str) try: partinstance = PartInstance.objects.get(part=part, color=color) except PartInstance.DoesNotExist: print "PartInstance not exist, creating" partinstance = PartInstance(color=color, part=part, user_override=True) partinstance.save() inventory = Inventory(partinstance = partinstance) inventory.save() def add_inventory_to_formset(i): i.inventory = inventory i.save() instances = location_formset.save(commit = False) map(add_inventory_to_formset, instances) previous_keywords = [] def process_kw_formset(i): # Add the inventory to each item and save it i.inventory = inventory i.save() # Save the keyword and value for populating next time d = {'keyword': i.keyword.pk, 'value': i.value} previous_keywords.append(d) instances = kw_formset.save(commit = False) map(process_kw_formset, instances) request.session['previous_keywords'] = previous_keywords if 'add_another' in request.POST: return redirect(add_inventory) else: return redirect(index) else: inventory_form = InventoryForm(prefix="inv") location_formset = LocationFormSet(prefix = "loc", queryset = LocationAmount.objects.none()) if 'previous_keywords' in request.session: # Use keywords from previous form, if they exist previous_keywords = request.session['previous_keywords'] del request.session['previous_keywords'] kw_formset = KeywordFormSet(prefix="kw", queryset=Keyword.objects.none(), initial=previous_keywords) else: kw_formset = KeywordFormSet(prefix="kw", queryset=Keyword.objects.none()) return render(request, 'add_inventory.html', {'inventory_form': inventory_form, 'location_formset': location_formset, 'kw_formset': kw_formset, })
def update_stock(request): Inventory.populate_stock() return HttpResponse('done!')
def get_inventories(request): inventories = Inventory.objects().order_by("-_id") return render(request, "list_inventories.html", {"inventories": inventories})
def handle(self, *args, **options): Inventory.populate() Inventory.populate_stock() self.stdout.write(self.style.SUCCESS('Successfully populated DB'))
def inventory_submit(request): # 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 = text_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() inventory_meta.inventory_str = inventory_str # 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 utils.is_postgres(): inventory_items_to_be_created.append(i_item) else: i_item.save() machine.last_inventory_update = timezone.now() inventory_meta.save() if utils.is_postgres(): InventoryItem.objects.bulk_create(inventory_items_to_be_created) return HttpResponse("Inventory submitted for %s.\n" % submission.get('serial')) return HttpResponse("No inventory submitted.\n")
def test_populate_stock(self): Inventory().populate_stock()