def item_create(replace_key=None): if replace_key: item = replace_key.get() else: url_safe_name = make_url_safe(request.form.get('name')) item = Item(id = url_safe_name) item.populate( name = request.form.get('name'), description = request.form.get('description'), count = int(request.form.get('count')) if request.form.get('count') else 1, prices = [float(request.form.get('price_int')) if request.form.get('price_int') else 0, float(request.form.get('price_ext')) if request.form.get('price_ext') else 0, float(request.form.get('price_com')) if request.form.get('price_com') else 0, float(request.form.get('price_buy')) if request.form.get('price_buy') else 0, ], tax_per_day = True if request.form.get('tax_per_day') else False, category = request.form.get('category'), ) id = item.put().id() file = request.files['file'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
def import_inventory(request): from models import PCGSNumberException shop = request.shop failures = [] if request.method == 'POST': remove_inventory = bool(request.POST['r'] == "True") if remove_inventory: items = Item.objects.filter(shop=shop) for item in items: item.delete() for file in request.FILES.getlist('file'): try: from xls_parser import CoinInventoryParser parser = CoinInventoryParser() (keys, products) = parser.parse_xls(file) for product in products: if product == []: continue try: Item.create_from_inventory(shop, keys, product) except PCGSNumberException: logging.critical("PCGSNumber not exists for product %s" % product) failures.append(product[0]) except Exception, e: logging.error(e)
def item_store(category_name): """Store new item in DB""" if 'username' not in login_session: return redirect(url_for('login')) category = Category.query.filter(Category.name == category_name).first() if category.author_id != login_session['user_id']: return render_template('401.html', name='item') form = ItemForm() form.category_id.choices = [(c.id, c.name) for c in Category.query.order_by('name')] form.category_id.data = category.id if form.validate_on_submit(): try: new_item = Item(form.name.data, form.description.data, category.id, login_session['user_id']) if 'image' in request.files and request.files['image']: filename = images.save(request.files['image']) new_item.image_name = filename db_session.add(new_item) db_session.commit() return redirect(url_for('item_view', category_name=category_name, item_name=form.name.data)) except IntegrityError: db_session.rollback() flash("Item name must be unique value") except Exception, e: db_session.rollback() print e flash("Database error encountered")
def create_digest(self, item_type, github_items): """ builds a DigestData instance filled with the digest """ issue_list = list(self.get_issues()) digest = DigestData(item_type) digest.user = self._user digest.repo = self._repository_name for github_item in github_items: if github_item.state == ItemStates.OPEN: digest.total_opened += 1 elif github_item.state == ItemStates.CLOSED: digest.total_closed += 1 digest.total_items += 1 item = Item() item.url = github_item.html_url item.label = '{}/{}#{}'.format(self._user, self._repository_name, github_item.number) item.title = github_item.title item.state = github_item.state github_user = github_item.user display_name = github_user.name or github_user.login if display_name not in digest.users: user = User() user.name = display_name user.gravatar = github_user.avatar_url digest.users[display_name] = user digest.items.setdefault(display_name, []).append(item) return digest
def on_message(self, message): data = json.loads(message) if "update_type" in data and data["update_type"] == "draw": board_id = data["board_id"] broadcastData = data self.broadcast(board_id, broadcastData, write_to_self=False) return message_type = data.get('message_type') board_id = data["board_id"] if message_type and message_type == 'user_update': self._update_user(board_id, data['username']) self._broadcast_user_display(board_id) elif message_type and message_type == 'board_name_update': name = self._update_board_name(board_id, data['name']) self._broadcast_board_name_update(board_id, name) else: board = Board.get(board_id) item = Item(**data["item"]) board.updateItem(item) board.save() broadcastData = { "update_type": "pos_change", "item": json.loads(item.to_json()) } self.broadcast(board_id, broadcastData, write_to_self=False)
def item_form(request, id=None): if id: item = get_object_or_404(Item, id=id, company=request.company) scenario = 'Update' else: item = Item(purchase_account=Account.objects.get(name='Purchase', company=request.company), sales_account=Account.objects.get(name='Sales', company=request.company), purchase_tax_scheme=TaxScheme.objects.get(name='No Tax', company=request.company), sales_tax_scheme=TaxScheme.objects.get(name='No Tax', company=request.company)) scenario = 'Create' if request.POST: form = ItemForm(data=request.POST, instance=item, company=request.company) if form.is_valid(): item = form.save(commit=False) item.company = request.company item.save() if request.is_ajax(): return render(request, 'callback.html', {'obj': ItemSerializer(item).data}) return redirect('/inventory/items/') else: form = ItemForm(instance=item, company=request.company) if request.is_ajax(): base_template = 'modal.html' else: base_template = 'dashboard.html' return render(request, 'item_form.html', { 'scenario': scenario, 'form': form, 'base_template': base_template, })
def create_item(request): """ @param request: @param id: @return: JSON for account for added Inventory Item """ item = Item(purchase_account=Account.objects.get(name='Purchase', company=request.company), sales_account=Account.objects.get(name='Sales', company=request.company), purchase_tax_scheme=TaxScheme.objects.get(name='No Tax', company=request.company), sales_tax_scheme=TaxScheme.objects.get(name='No Tax', company=request.company)) scenario = 'Create' for query in request.GET: setattr(item, query, request.GET[query]) if request.POST: form = ItemForm(data=request.POST, instance=item, company=request.company) if form.is_valid(): item = form.save(commit=False) item.company = request.company item.save() if request.is_ajax(): return render(request, 'callback.html', {'obj': InventoryAccountSerializer(item.account).data}) return redirect('/inventory/items/') else: form = ItemForm(instance=item, company=request.company) form.hide_field(request) if request.is_ajax(): base_template = 'modal.html' else: base_template = 'dashboard.html' return render(request, 'item_form.html', { 'scenario': scenario, 'form': form, 'base_template': base_template, })
def post(self): user = users.get_current_user() if user == None: self.redirect("/") return # get category information category = self.request.get('category') item = self.request.get('newItem') if item != "": cs = Category.all() cs.filter('user ='******'category =', category) # get category c = cs.get() if c != None: items = Item.all() items.filter('item =', item) items.ancestor(c.key()) if items.get() == None: newItem = Item(item = item, win = 0, lose = 0, rate = 0, parent = c.key()) # post a new item newItem.put() # save else: errorMessage = "Item %s already exists!" % item self.redirect("/manageCategory?category=%s&error=%s" % (category, errorMessage)) return self.redirect("/manageCategory?category=%s" % category)
def test_saving_and_retrieving_items(self): list_ = List() list_.save() first_item = Item() first_item.text = 'The first (ever) list item' first_item.list = list_ first_item.save() second_item = Item() second_item.text = 'Item the second' second_item.list = list_ second_item.save() saved_list = List.objects.first() self.assertEqual(saved_list, list_) saved_items = Item.objects.all() self.assertEqual(saved_items.count(), 2) first_saved_item = saved_items[0] second_saved_item = saved_items[1] self.assertEqual(first_saved_item.text, 'The first (ever) list item') self.assertEqual(first_saved_item.list, list_) self.assertEqual(second_saved_item.text, 'Item the second') self.assertEqual(second_saved_item.list, list_)
def fetch(self): self.build_service('drive', 'v3') timeMin = self.date_dt.isoformat() timeMax = self.next_date_dt.isoformat() query = "(viewedByMeTime > '%s' and viewedByMeTime < '%s') OR (createdTime > '%s' and createdTime < '%s' and '%s' in owners)" % ( timeMin, timeMax, timeMin, timeMax, self.user.email) items = [] results = self.service.files().list( orderBy='modifiedTime', pageSize=self.limit, spaces='drive,photos', fields='files(createdTime,description,id,kind,viewedByMeTime,modifiedTime,name,spaces,webViewLink,thumbnailLink),kind', q=query).execute() for f in results.get('files', []): spaces = f.get('spaces') is_image = 'photos' in spaces type = SERVICE.DOCUMENT if not is_image else SERVICE.PHOTO webViewLink = f.get('webViewLink') thumbnailLink = f.get('thumbnailLink') item = Item(svc=SERVICE.GDRIVE, title=f.get('name'), id=f.get('id'), image=thumbnailLink, details=f.get('description'), type=type) if is_image: logging.debug(f) items.append(item.json()) return items
def create(): form = CreateItemForm(request.form) if request.method == 'POST' and form.validate(): sheetmusic_id = form.sheetmusic_id.data sheetmusic = Sheetmusic.query.filter_by(id=sheetmusic_id).one() new_item = Item() form.populate_obj(new_item) new_item.user_id = g.user.id g.db.add(new_item) g.db.commit() for file in request.files.getlist('images'): if file: ext = file.filename.rsplit('.', 1)[-1] filename = g.user.username + '_' + str(uuid4()) + '.' + ext image = ItemImage(filename) save_image(file, filename) new_item._images.append(image) g.db.commit() flash("You just made a new item!", "success") return redirect(url_for('items.index', item_id=new_item.id)) sheetmusic_id = int(request.args.get('sheetmusic_id', 0)) if sheetmusic_id: form.sheetmusic_id.data = sheetmusic_id return render_template('items/create_item.html', form=form)
def test_update(self): order = Order(name="Dummy Order") order.save() for i in range(2): item = Item(name="Item %i" % i, sku=str(i) * 13, price=D("9.99"), order=order, status=0) item.save() tag = Tag(name="Test", content_object=order) tag.save() res = self.client.get("/inlines/1/") self.assertEqual(res.status_code, 200) order = Order.objects.get(id=1) self.assertEquals(2, order.item_set.count()) self.assertEquals("Item 0", order.item_set.all()[0].name) data = { "name": u"Dummy Order", "item_set-TOTAL_FORMS": u"4", "item_set-INITIAL_FORMS": u"2", "item_set-MAX_NUM_FORMS": u"", "item_set-0-name": "Bubble Bath", "item_set-0-sku": "1234567890123", "item_set-0-price": D("9.99"), "item_set-0-status": 0, "item_set-0-order": 1, "item_set-0-id": 1, "item_set-1-name": "Bubble Bath", "item_set-1-sku": "1234567890123", "item_set-1-price": D("9.99"), "item_set-1-status": 0, "item_set-1-order": 1, "item_set-1-id": 2, "item_set-2-name": "Bubble Bath", "item_set-2-sku": "1234567890123", "item_set-2-price": D("9.99"), "item_set-2-status": 0, "item_set-2-order": 1, "item_set-3-DELETE": True, "tests-tag-content_type-object_id-TOTAL_FORMS": 3, "tests-tag-content_type-object_id-INITIAL_FORMS": 1, "tests-tag-content_type-object_id-MAX_NUM_FORMS": u"", "tests-tag-content_type-object_id-0-name": u"Test", "tests-tag-content_type-object_id-0-id": 1, "tests-tag-content_type-object_id-0-DELETE": True, "tests-tag-content_type-object_id-1-name": u"Test 2", "tests-tag-content_type-object_id-2-name": u"Test 3", } res = self.client.post("/inlines/1/", data, follow=True) self.assertEqual(res.status_code, 200) order = Order.objects.get(id=1) self.assertEquals(3, order.item_set.count()) self.assertEquals(2, Tag.objects.count()) self.assertEquals("Bubble Bath", order.item_set.all()[0].name)
def test_update(self): order = Order(name='Dummy Order') order.save() for i in range(2): item = Item(name='Item %i' % i, sku=str(i) * 13, price=D('9.99'), order=order, status=0) item.save() tag = Tag(name='Test', content_object=order) tag.save() res = self.client.get('/inlines/1/') self.assertEqual(res.status_code, 200) order = Order.objects.get(id=1) self.assertEquals(2, order.item_set.count()) self.assertEquals('Item 0', order.item_set.all()[0].name) data = { 'name': u'Dummy Order', 'item_set-TOTAL_FORMS': u'4', 'item_set-INITIAL_FORMS': u'2', 'item_set-MAX_NUM_FORMS': u'', 'item_set-0-name': 'Bubble Bath', 'item_set-0-sku': '1234567890123', 'item_set-0-price': D('9.99'), 'item_set-0-status': 0, 'item_set-0-order': 1, 'item_set-0-id': 1, 'item_set-1-name': 'Bubble Bath', 'item_set-1-sku': '1234567890123', 'item_set-1-price': D('9.99'), 'item_set-1-status': 0, 'item_set-1-order': 1, 'item_set-1-id': 2, 'item_set-2-name': 'Bubble Bath', 'item_set-2-sku': '1234567890123', 'item_set-2-price': D('9.99'), 'item_set-2-status': 0, 'item_set-2-order': 1, 'item_set-3-DELETE': True, 'tests-tag-content_type-object_id-TOTAL_FORMS': 3, 'tests-tag-content_type-object_id-INITIAL_FORMS': 1, 'tests-tag-content_type-object_id-MAX_NUM_FORMS': u'', 'tests-tag-content_type-object_id-0-name': u'Test', 'tests-tag-content_type-object_id-0-id': 1, 'tests-tag-content_type-object_id-0-DELETE': True, 'tests-tag-content_type-object_id-1-name': u'Test 2', 'tests-tag-content_type-object_id-2-name': u'Test 3', } res = self.client.post('/inlines/1/', data, follow=True) self.assertEqual(res.status_code, 200) order = Order.objects.get(id=1) self.assertEquals(3, order.item_set.count()) self.assertEquals(2, Tag.objects.count()) self.assertEquals('Bubble Bath', order.item_set.all()[0].name)
def save_edited_category(): cat_name = request.form.get("category") key = request.form.get("key") existing = Category.all().filter("owner =", users.get_current_user()) for e in existing: if e.title.lower() == cat_name.lower(): if not str(e.key()) == key: error = "You already have a category with that name. Please choose a different name" return Response(status=400) category = Category.get(key) items_from_form = request.form.get("items").split(",") old_items_from_db = Item.all().ancestor(category) for item in old_items_from_db: if not item.title in items_from_form: db.delete(item) else: items_from_form.remove(item.title) for new_item in items_from_form: if not new_item == "": i = Item(parent=category, title=new_item) i.put() category.title = request.form.get("category") category.put() return jsonify(new_items=items_from_form)
def test_format_item_to_json(self): item = Item(1, "test name", "Medium", "This is a test description") item.save() results = item.to_json() expected_results = dict(id=1, user_id=1, name="test name", priority="Medium", description="This is a test description") self.assertEqual(expected_results, results)
def post_item(request): if request.method == 'POST': form = ItemForm(request.POST, request.FILES) if form.is_valid(): m_tags = form.cleaned_data['item_tags'] m = Item( name=form.cleaned_data['item_name'], # type=form.cleaned_data['item_type'], # item_image=request.FILES['item_image'], image_first = form.cleaned_data['image_first'], image_second= form.cleaned_data['image_second'], image_third= form.cleaned_data['image_third'], looking_for = True if 'True' == form.cleaned_data['item_sellOrLookFor'] else False, category = form.cleaned_data['item_category'], #price=form.cleaned_data['item_price'], negotiable=form.cleaned_data['item_negotiable'], owner=request.user, description=form.cleaned_data['item_description'] ) m.save() print "item has been saved with item_id "+str(m.pk) print m_tags m.tags.add(*m_tags) # return my_items(request) return HttpResponseRedirect('/') else: form = ItemForm() return render_to_response('post_item.html', {'form': form, 'user': request.user}, context_instance=RequestContext(request))
def post(self): form = AddItemForm() item = Item() if form.validate_on_submit(): ar_title = Titles() fr_title = Titles() en_title = Titles() ar_title.title = form.ar_title.data.strip() ar_title.lang = 'ar' fr_title.title = form.fr_title.data.strip() fr_title.lang = 'fr' en_title.title = form.en_title.data.strip() en_title.lang = 'en' item.titles.append(ar_title) item.titles.append(fr_title) item.titles.append(en_title) item.description = form.description.data item.submitter = User.objects.get(id=current_user.id) else: flash('upload unsuccessful', 'error') return render_template('items/add_item.html', form=form) uploaded_files = request.files.getlist("files") thumbnail = request.files['thumbnail'] thumbnail_name = secure_filename(thumbnail.filename) if thumbnail and allowed_thumbnails(thumbnail_name): ext = thumbnail.mimetype.split('/')[-1] # use the 'thumbnail' name for all thumbnails filename = '.'.join(["thumbnail", ext]) item.thumbnail.put(thumbnail.stream, content_type=thumbnail.mimetype, filename=filename) for file in uploaded_files: # Make the filename safe, remove unsupported chars filename = secure_filename(file.filename) # Check if the file is one of the allowed types/extensions if file and allowed_file(filename): # put the file in the ListField. # see https://gist.github.com/tfausak/1299339 file_ = GridFSProxy() file_.put(file.stream, content_type=file.mimetype, filename=filename) item.files.append(file_) # Save the thing item.save() flash('upload successful') return render_template('items/add_item.html', form=form)
def updateLocalDB(request): cursor = connections['cineca'].cursor() # Cursor connessione Cineca cursorLocal = connections['default'].cursor() # Cursor DB locale # Seleziona tutti i dati necessari dal DB remoto cursor.execute( "SELECT \ INV.ID_INVENTARIO_BENI,\ INV.DS_BENE,\ MOV.DT_REGISTRAZIONE_BUONO,\ INV.VALORE_CONVENZIONALE,\ SPA.DS_SPAZIO,\ INV.DT_INI_AMMORTAMENTO,\ INV.VALORE_CONVENZIONALE - (LEAST((extract(year from sysdate) - EXTRACT(year FROM INV.DT_INI_AMMORTAMENTO)),AMM.NUM_ANNUALITA) * (INV.VALORE_CONVENZIONALE / AMM.NUM_ANNUALITA)) AS VALORE_RESIDUO\ FROM\ (((V_IE_CO_MOVIMENTI_BENE MOV RIGHT JOIN V_IE_CO_INVENTARIO_BENI INV\ ON MOV.ID_INVENTARIO_BENI = INV.ID_INVENTARIO_BENI) LEFT JOIN\ V_IE_AC_SPAZI SPA ON INV.CD_UBICAZIONE = SPA.CD_SPAZIO) INNER JOIN\ V_IE_CO_AS_TIP_AMM_CAT_GRP_INV AMM on INV.CD_CATEG_GRUPPO = AMM.CD_CATEG_GRUPPO )\ WHERE\ (AMM.ESERCIZIO - EXTRACT(year FROM INV.DT_INI_AMMORTAMENTO)) = 0\ ORDER BY\ MOV.ID_INVENTARIO_BENI DESC" ) rows = rows_to_dict_list(cursor) # Scorre tutti i dati riga per riga for row in rows: # Per ogni riga vede se l'oggetto esiste gia' nel database try: #print "obj ",row['ID_INVENTARIO_BENI'],"val res: ",row['VALORE_RESIDUO'] item = Item.objects.get(item_id=row['ID_INVENTARIO_BENI']) # Se l'oggetto esiste i dati vengono aggiornati item.item_id = row['ID_INVENTARIO_BENI'] item.description = row['DS_BENE'] if row['DS_BENE'] else '' item.purchase_date = row['DT_REGISTRAZIONE_BUONO'] if row['DT_REGISTRAZIONE_BUONO'] is not None else '0001-01-01 00:00' item.price = row['VALORE_CONVENZIONALE'] if row['VALORE_CONVENZIONALE'] else -1 item.location = row['DS_SPAZIO'] if row['DS_SPAZIO'] is not None else '' item.depreciation_starting_date = row['DT_INI_AMMORTAMENTO'] if row['DT_INI_AMMORTAMENTO'] else '0001-01-01 00:00' item.residual_value = row['VALORE_RESIDUO'] if row['VALORE_RESIDUO'] is not None else -1 # item = Item(None,item_id,description,purchase_date,price,location,depreciation_starting_date) item.save() except Item.DoesNotExist: # Se non esiste viene creato un nuovo oggetto item_id = row['ID_INVENTARIO_BENI'] description = row['DS_BENE'] if row['DS_BENE'] else '' purchase_date = row['DT_REGISTRAZIONE_BUONO'] if row['DT_REGISTRAZIONE_BUONO'] is not None else '0001-01-01 00:00' price = row['VALORE_CONVENZIONALE'] if row['VALORE_CONVENZIONALE'] else -1 location = row['DS_SPAZIO'] if row['DS_SPAZIO'] is not None else '' depreciation_starting_date = row['DT_INI_AMMORTAMENTO'] if row['DT_INI_AMMORTAMENTO'] else '0001-01-01 00:00' residual_value = row['VALORE_RESIDUO'] if row['VALORE_RESIDUO'] is not None else -1 item = Item(None,item_id,description,purchase_date,price,location,depreciation_starting_date,residual_value) item.save() return redirect ('showLocalDB')
def post(self): name = self.request.get('name') itemNum = self.request.get('itemNum') origin = self.request.get('origin') item_post = Item(name=name, itemNum=itemNum, origin=origin) item_post.put() self.redirect('/')
def fetch(): if not request.user or not session.get('token'): return redirect(url_for('login')) auth = github.get_session(token=session['token']) for feed in request.user.feeds: resp = auth.get(feed.url).json() for resp_item in resp: Item.parse_and_add(resp_item, feed, request.user) return redirect(url_for('index'))
def get(self): user = users.get_current_user() items = Item.query().filter(Item.owner == user.email()).filter(Item.type == "Task").order(-Item.date).fetch() items += Item.query().filter(Item.owner == user.email()).filter(Item.type == "Knowledge").order(-Item.date).fetch() template_values = { 'items':items, 'user':user } self.render("user_store.html", (template_values))
def item_thumb(request, slug): item = cache.get(Item.get_cache_key(slug), None) if not item: item = get_object_or_404(Item, slug=slug) if item.cacheable: cache.set(Item.get_thumb_cache_key(slug), item, app_settings.GALLERY_CACHE_TIMEOUT) return HttpResponse(item.thumb, mimetype=item.mimetype)
def get(self): user = users.get_current_user() items = Item.query().filter(Item.type == 'Task').order(-Item.date).fetch() items += Item.query().filter(Item.type == 'Knowledge').order(-Item.date).fetch() template_values = { 'items':items, 'user': user } self.render("store.html", (template_values))
def item_delete(request, item_id): item = get_object_or_404(Item, pk=item_id) if item.shop != request.shop: raise Http404 item.delete() Item.update_latest_item(request.shop) request.flash['message'] = unicode(_("Item successfully deleted.")) request.flash['severity'] = "success" return HttpResponseRedirect(reverse("inventory_items"))
def init_test_data(): # add item1 item1 = Item("mario", 1000, "a happy mario toy", "1.png", 12, 1, 10) dict1 = item1.to_dict() redis_manager.set_dict(dict1, 12, 1) # add item2 item2 = Item("doraamon", 1500, "a cute doraamon", "2.png", 12, 2, 15) dict2 = item2.to_dict() redis_manager.set_dict(dict2, 12, 2)
def post(self): checklist = Checklist.get(Key(self.request.get('cl_key'))) if not helpers.checkPermissionAndRespond(self, cl=checklist): return item = Item( title=self.request.get('title'), checklist=checklist, deleted=False) item.put() helpers.createResponse(self, 'new_item.html', {'item': item})
def count_increase(self, book_id, **kwargs): try: item = self.session.query(Item).filter(Item.book_id == book_id).one() except: item = Item() item.book_id = book_id item.count_guest += kwargs.get('count_guest', 0) item.count_visit += kwargs.get('count_visit', 0) item.count_download += kwargs.get('count_download', 0) item.save()
def test_context(self): order = Order(name="Dummy Order") order.save() for i in range(10): item = Item(name="Item %i" % i, sku=str(i) * 13, price=D("9.99"), order=order, status=0) item.save() res = self.client.get("/modelformset/simple/") self.assertTrue("object_list" in res.context) self.assertEquals(len(res.context["object_list"]), 10)
def post(self): try: newitem = Item(name = self.request.get('name'), price = int(self.request.get('price')), quantity = int(self.request.get('quantity')), description = self.request.get('description')) newitem.put() except ValueError: return self.error(500) self.redirect('/')
def test_context(self): order = Order(name='Dummy Order') order.save() for i in range(10): item = Item(name='Item %i' % i, sku=str(i) * 13, price=D('9.99'), order=order, status=0) item.save() res = self.client.get('/modelformset/simple/') self.assertTrue('object_list' in res.context) self.assertEquals(len(res.context['object_list']), 10)
def test_add_an_item(self): """ Create an Item and add it to the database """ items = Item.all() self.assertEqual(items, []) item = Item(order_id=1, product_id=1, name="wrench", quantity=1, price=10.50) self.assertEqual(item.id, None) item.save() self.assertEqual(item.id, 1) items = Item.all() self.assertEqual(len(items), 1)
def items(): """ GET: Shows all items POST: Creates a new item. :return: GET: the appropriate template, POST: redirect to items """ if request.method == "GET": db_session = DBSession() items_all = db_session.query(Catalog, Item, User).join(Item.catalog).join(Item.user) items_count = items_all.count() db_session.close() return render_template('items/items.html', tuple=items_all, count=items_count) elif request.method == "POST": if not is_signed_in(): flash(Markup(MUST_SIGN_IN)) return redirect(request.referrer) db_session = DBSession() name = request.form['name'] name = name.strip() description = request.form['description'] description = description.strip() if not name or not description: flash(EMPTY_FORM) redirect(request.referrer) catalog_id = request.form['catalog_id'] email = session['idinfo']['email'] user = db_session.query(User).filter_by(email=email).first() item = Item(name=name, description=description, catalog_id=catalog_id, user_id=user.id) db_session.add(item) db_session.commit() db_session.close() return redirect(url_for('items'))
def addItem(category_name): """Method for Adding and Item""" if request.method == 'GET': categories = session.query(Category).all() return render_template('addItem.html', categories=categories, category_name=category_name) elif request.method == 'POST': categories = session.query(Category).all() category_names = request.form['category_name'] try: item_name = request.form['name'] item_description = request.form['description'] item_category = request.form['category'] item_to_add = Item(item_name=item_name, description=item_description, category_id=item_category, created_by=login_session['user_id']) except: return render_template('addItem.html', categories=categories, category_name=category_names) try: session.query(Item).filter_by(item_name=item_name).one() return render_template('addItem.html', categories=categories, category_name=category_names) except: if item_name == '' or item_description == '': return render_template('addItem.html', categories=categories, category_name=category_names) else: try: session.query(Category).filter_by(id=item_category).one() session.add(item_to_add) session.commit() return redirect(url_for('home')) except: return render_template('addItem.html', categories=categories, category_name=category_names)
def view_list(request, list_id): list_ = List.objects.get(id=list_id) error = None if request.method == 'POST': try: item = Item(text=request.POST['item_text'], list=list_) item.full_clean() item.save() # Item.objects.create(text=request.POST['item_text'], list=list_) return redirect(list_) except ValidationError: error = "You can't have an empty list item" # items=Item.objects.filter(list=list_) return render(request, 'list.html', {'list': list_, 'error': error})
def add_item(category_name): """ On GET, Render a form to add a new item to the catalog. On POST, save the new item to the database. """ # Check if user is logged in to enable adding a new item if 'username' not in login_session: flash('You must be logged in to add a new item!') return redirect('/login') # Add new item if request.method == 'POST': user = get_user_info_by_emaild(login_session['username']) # Check which button was clicked, Add or Cancel # If Add/Submit button clicked, add the item to the database if 'submit' in request.form.keys() and request.form['submit'] == "Add": category_id = request.form['category'] category = session.query(Category).filter_by(id=category_id).first() new_item = Item(title=request.form['title'], description=request.form['description'], cat_id=category_id, category=category, user_id=user.id, user=user) session.add(new_item) session.commit() flash('New Item %s Successfully Created') # render a page that lists all the items of the newly added item's category return redirect(url_for('show_items_for_category', category_name=category.name, category_id=category_id)) else: # render a page that lists all the items of the newly added item's category return redirect(url_for('show_latest_items')) else: # Serve add item form to client - GET request categories_list = session.query(Category).order_by(asc(Category.name)).all() # Check if category is already selected, else set default to Basketball if category_name is None: category_name = "Basketball" return render_template('addNewItem.html', categories_list=categories_list, selected_category=category_name)
def add_item(): if request.method == 'GET': # Set state for CSRF protection state = utilities.get_state() session['state'] = state categories = Category.query.all() return render_template('new-item.html.j2', categories=categories, state=state, page='New Item') else: form = request.get_json() try: form_category = form['category'] description = form['description'] name = form['title'] # checking for incomplete forms except: abort(418) if not form_category or not description or not name: # Useful response ommitted: handled in js abort(418) # CSRF check if form['state'] != session['state']: abort(401) # Check db for category try: category = Category.search(form_category) assert category is not None # Make category if not in db except: category = Category(form_category) db.session.add(category) db.session.commit() user = User.by_id(session['user']) it = Item(category, name, description, user) db.session.add(it) db.session.commit() flash('{0} has been added to the catalog'.format(it.name), 'success') return json.jsonify({'href': url_for('item.item', item_id=it.id)})
def hn_fetch_item(self, hn_id, item_info): self.STAT_ITEM_FROM_HN += 1 # Recurse to get the top_parent parent_id = item_info.get('parent') if parent_id is None: logging.info('Failed to find the top parent for ' + str(hn_id)) self.STAT_ITEM_NO_TOP_PARENT += 1 top_parent = None parent_item = None else: parent_item = self.fetch_item_or_article_by_id(parent_id) # When an article is returned, we know we've hit the top if isinstance(parent_item, Article): # logging.info('Found top parent' + str(parent_id)) top_parent = parent_item parent_item = None elif parent_item is None: top_parent = None elif parent_item.top_parent is None: top_parent = None else: # the top_parent is at least 1 grandparent away, or not found top_parent = parent_item.top_parent item = Session().query(Item).filter(Item.hn_id == hn_id).first() if not item: submitter_id = item_info.get('by') submitter = self.query_or_create_user(submitter_id) item = Item( hn_id=hn_id, submitter=submitter, type=item_info.get('type'), parent=parent_item, top_parent=top_parent ) Session().add(item) self.STAT_ITEM_CREATED += 1 return item
def test_parse_tree(): dataset = gd() tree = None tokens = {} with open('trie.json', 'r') as f: tree = json.load(f) def find_matches(nodes, best_match, value, tokenizer): for node in nodes: m = re.match(node['pattern'], value) if m: best_match = node['pattern'] if re.match(best_match + '$', value): tokenizer[value] = m.groups() return best_match find_matches(node['children'], best_match, value, tokenizer) for item in dataset: best_match = tree['pattern'] best_match = find_matches(tree['children'], best_match, item, tokens) with open('expanded_descriptions.json', 'w') as f: tree = json.dump(tokens, f) for token in tokens: length = len(tokens[token]) session.add( Item( name=token or 'None', department=tokens[token][0] if length > 0 else None, product_type=tokens[token][1] if length > 1 else "Name", q1=tokens[token][2] if length > 2 else None, q2=tokens[token][3] if length > 3 else None, q3=tokens[token][4] if length > 4 else None, q4=tokens[token][5] if length > 5 else None, q5=tokens[token][6] if length > 6 else None, q6=tokens[token][7] if length > 7 else None, )) session.commit()
def defesa (self): defesa = 0 try: defesa += Item.get_by_id(self.atacado.bra_dir).defesa defesa += Item.get_by_id(self.atacado.bra_esq).defesa defesa += Item.get_by_id(self.atacado.cabeca).defesa defesa += Item.get_by_id(self.atacado.peito).defesa defesa += Item.get_by_id(self.atacado.perna).defesa defesa += Item.get_by_id(self.atacado.sapato).defesa except : print(IntegrityError) return 1 defesa += randint(self.atacado.resiliencia, self.atacado.resiliencia + defesa) return defesa
def test_delete_order__fail_not_own_order(self): user = add_user('*****@*****.**', TEST_USER_PSW) addr_A = add_address(user=user) item1 = Item.create( uuid='429994bf-784e-47cc-a823-e0c394b823e8', name='mario', price=20.20, description='svariati mariii', availability=2, category='scarpe', ) order1 = Order.create(delivery_address=addr_A, user=user) order1.add_item(item1, 2) user_B = add_user('*****@*****.**', TEST_USER_PSW) path = 'orders/{}'.format(order1.uuid) resp = open_with_auth(self.app, API_ENDPOINT.format(path), 'DELETE', user_B.email, TEST_USER_PSW, None, None) assert resp.status_code == UNAUTHORIZED
def test_delete_item(self): """ Deleting an Item from an Wishlist""" item = Item.find_by_name('toilet paper')[0] # Save the current number of items for assertion item_count = self.get_item_count() resp = self.app.delete('/wishlists/{}/items/{}'.format( item.wishlist_id, item.id), content_type='application/json') self.assertEqual(resp.status_code, status.HTTP_204_NO_CONTENT) self.assertEqual(len(resp.data), 0) new_count = self.get_item_count() self.assertEqual(new_count, item_count - 1) resp = self.app.delete('/wishlists/{}/items/{}'.format(5, item.id), content_type='application/json') self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND) resp = self.app.delete('/wishlists/{}/items/{}'.format(2, 1), content_type='application/json') self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)
def newItem(): """On a GET request show the new itempage (depending on whether the requestor has logged in). On a POST request, create the new item in the database. """ if 'username' not in login_session: return redirect('/login') if request.method == 'POST': newItemCat_id = session.query(Category).filter_by( name=request.form['category']).one() newItem = Item( title=request.form['title'], description=request.form['description'], cat_id=newItemCat_id.id, user_id=login_session['user_id']) session.add(newItem) flash('New Item %s Successfully Created' % newItem.title) session.commit() return redirect(url_for('showCatalog')) else: categories = session.query(Category).all() return render_template('newitem.html', categories=categories)
def create_item(category): """ Generate a page for creating the item for the category. Create the item according to the form if POST request. :param category: name of the category which to render page by """ category = Category.query.filter(Category.name == category).first_or_404() form = ItemForm(request.form) # Validate the form and create the item if POST request. if request.method == 'POST' and form.validate(): item = Item(category=category) form.populate_obj(item) db.session.add(item) db.session.commit() return redirect( url_for('get_item', category=category.name, item=item.name)) return render_template('items/create.html', category=category.name, form=form)
def submit(self): if not self.line_edit.text(): QMessageBox.information(self, "", "必须指定名称!") return else: if self.item is None: self.item = Item(name='', description='', x=self.event.x(), y=self.event.y(), place=self.parent.place) self.item.name = self.line_edit.text() self.item.description = self.textedit.toPlainText() session.add(self.item) session.commit() print(self.item, self.parent.items) if self.item not in self.parent.items: self.parent.items.append(self.item) self.parent.image_label.add_button(self.item) self.parent.flush() self.accept()
def newItem(user): error = None form = ItemForm() if request.method == 'POST': if form.validate_on_submit(): if Item.query.filter_by(title=form.title.data).first(): error = 'Item is already in our records' else: item = Item(title=form.title.data, description=form.description.data, cat_name=form.cat_name.data, created_by=user['user_id']) db.session.add(item) db.session.commit() # Adds new entry to Algolia's index algolia_index.add_objects([item.serialize]) redirect(url_for('index')) else: error = 'All fields are required' params = dict(user=user, form=form, error=error) return render_template('newItem.html', **params)
def results(key,expired=None): my_votes = {} my_comments = {} user_comments = {} category = Category.get(key) items = Item.all().ancestor(category).order('-wins').order('losses') count = 0 for i in items: item = UserVote.all().ancestor(i).order('-wins').order('losses').filter('voter =', users.get_current_user()).get() if not item: my_votes[count] = [i.title, "-", "-"] else: my_votes[count] = [i.title, item.wins, item.losses] # the count helps maintain the order -wins and losses count += 1 for c in items: user_comments[c.title] = UserComment.all().ancestor(c) my_comment = UserComment.all().ancestor(c).filter('commenter =',users.get_current_user()).get() if my_comment: my_comments[c.title] = my_comment.comment return render_template('results.html',items=items, key=key, title=category.title, owner=category.owner.email(), my_votes=my_votes, my_comments=my_comments, user_comments=user_comments,expired=expired)
def editItem(): # check if item is authorized to be modified item = getDbSession().query(Item).filter_by(id=request.form['id']).one() print 'login session id ' + login_session['id'] print 'udser id ' + item.user_id if login_session['id'] == item.user_id: print('Authorized') item = Item(request.form['id'], request.form['name'], request.form['description'], request.form['category']) update(item) return redirect("/index/") else: print('Not authorized') closeDbSession() flash( 'You are not authorized to edit this item.Please create your own item in order to edit.' ) return redirect("/index/")
def test_modify_item__failure_user_is_not_superuser(self): user = self.create_user() item = self.create_item() new_data = { 'name': 'item', 'price': 10, 'description': 'info product', 'category': 'product category', 'availability': 1 } resp = self.open_with_auth('/items/{}'.format(item.uuid), 'put', user.email, 'p4ssw0rd', data=new_data) assert resp.status_code == UNAUTHORIZED item_from_db = Item.get(uuid=item.uuid).json() assert item.json() == item_from_db
def newItem(category_id): """create a new item in the database under a given category""" # check for user login if 'username' not in login_session: return redirect('/login') form = ItemForm() # handle the POST request user = session.query(User).filter_by(username=login_session['username']).one() if form.validate_on_submit(): name = form.name.data photo = form.photo_filename.data description = form.description.data createdItem = Item(name=name, photo_filename=photo, description=description, category_id=category_id) session.add(createdItem) session.commit() flash('New {} tree created!'.format(name), 'alert alert-warning') return redirect(url_for('showItems', category_id=category_id)) # handle the GET request return render_template('newItems.html', form=form, user=user, category=category_id)
def new_category_item(category_name): category = session.query(Category).filter_by(name=category_name).first() if login_session['user_id'] != category.user_id: return "<script>function myFunction() \ {alert('You are not authorized to add items to this category. \ Please create your own category in order to add items.');} \ </script><body onload='myFunction()''>" if request.method == 'POST': newItem = Item(title=request.form['title'], description=request.form['description'], category_id=category.id, user_id=category.user_id) session.add(newItem) session.commit() flash("item created") return redirect( url_for('category_items_index', category_name=category_name)) else: return render_template('new_category_item.html', category_name=category_name)
def create_item(): """ Create a new item for the catalog """ s = Signer('secret_key') user_id = s.unsign(login_session.get('_session_id')) category_list = session.query(Category).all() if request.method == 'POST': new_item = Item(name=request.form['name'], description=request.form['description'], category_id=request.form['category'], created_by=user_id, price=request.form['price']) session.add(new_item) try: session.commit() except IntegrityError: app.logger.error("Error: {}".format(IntegrityError)) flash("Created new catalog item.") return redirect(url_for('get_categories')) return render_template('createitem.html', category_list=category_list)
def newCategoryItem(category): selectedCategory = session.query(Category).filter_by(name=category).one() if 'username' not in login_session: return redirect('/login') if selectedCategory.user_id != login_session['user_id']: return "<script>function myFunction(){alert('You are not authorized\ to add Item to this category. Please make item addition to your\ own categories.');}</script><body onload='myFunction()''>" if request.method == 'POST': newItem = Item(user_id=login_session['user_id'], title=request.form['title'], description=request.form['description'], cat_id=selectedCategory.id) session.add(newItem) session.commit() return redirect( url_for('categoryItems', category=selectedCategory.name)) else: return render_template('newcategoryitem.html', category=selectedCategory)
def item_new(): if request.method == 'POST': # store form data try: item = vh.item_from_form(Item(), request.form, user_id=login_session.get('user_id')) except ValueError as e: return "Database validation error: " + str(e) except SQLAlchemyError as e: # todo: log error, but don't display detailed message # for security reasons return "Database error: " + str(e) # store image file file_storage_err = vh.store_item_pic(item, request.files['picture']) if file_storage_err is not None: return file_storage_err return redirect(url_for('home')) else: categories = session.query(Category).all() return render_template('item_add.html', categories=categories)
def newItem(category_id): if 'username' not in login_session: return redirect('/login') category = session.query(Category).filter_by(id=category_id).one() creator = getUserInfo(category.user_id) if(creator.id != login_session['user_id']): flash("You did not create this category!") return redirect(url_for('showMenu')) if request.method == 'POST': item = Item( name=request.form['name'], description=request.form['description'], user_id=login_session['user_id'], category_id=category.id ) session.add(item) session.commit() flash("Item successfully created!") return redirect(url_for('showMenu')) else: return render_template('new_item.html', category=category)
def post(self): parser = reqparse.RequestParser() parser.add_argument('name', type=str, required=True) parser.add_argument('price', type=int, required=True) parser.add_argument('description', type=str, required=True) parser.add_argument('category', type=str, required=True) args = parser.parse_args(strict=True) try: utils.non_empty_str(args['name'], 'name') except ValueError: return None, BAD_REQUEST obj = Item.create( uuid=uuid.uuid4(), name=args["name"], price=args["price"], description=args["description"], category=args["category"] ) return obj.json(), CREATED
def new_item(): form = ItemForm() if form.validate_on_submit(): product = Product.query.filter_by(name=form.product_id.data).first() slist = Slist.query.filter_by(name=form.list_id.data).first() #product_id=prod.id shop_id = form.shop_id.data qnty = form.quantity.data price = form.price.data chk = False notes = form.notes.data item = Item(product=product, shop=shop_id, qnty=qnty, price=price, chk=chk, notes=notes, slist=slist) db.session.add(item) db.session.commit() return redirect(url_for('list_all'))
def create_item(): request_json = request.json print(request_json) item_type = request_json.get('itemType') quality = request_json.get('quality') owner = request_json.get('owner') name = request_json.get('name') try: item = Item(itemType=item_type, quality=quality, owner=owner, name=name) except: return '', HTTPStatus.CONFLICT print(item) db.session.add(item) db.session.commit() return jsonify(item), HTTPStatus.CREATED
def add_edited(self): # add the last edited field to each items = Item.query() stamp = datetime.now() dirty = False for it in items: try: it.edited = stamp it.save() except: it.votesUp = 0 dirty = True try: if not it.votesDown > 0: it.votesDown = 0 dirty = True except: it.votesDown = 0 dirty = True if dirty: it.save()
def post(self): if is_administrator(): try: logging.info("SyncToProd") seed_user = None for u in User.query(): if 'pegah' in u.auth_ids: seed_user = u.key break if seed_user: logging.info("SyncToProd seed user") url = 'https://rayv-app.appspot.com/admin/put_place_api' place_list = json.loads(self.request.params['list']) for place in place_list: it = Item.get_by_id(place) logging.info("SyncToProd sending " + it.place_name) form_fields = place.id_to_json() vote = Vote.query(Vote.voter == seed_user, Vote.item == it.key).get() if vote: form_fields['myComment'] = vote.comment form_fields['voteScore'] = vote.vote else: form_fields['voteScore'] = VoteValue.VOTE_LIKED form_fields['myComment'] = "" form_data = urllib.urlencode(form_fields) result = urlfetch.fetch( url=url, payload=form_data, method=urlfetch.POST, headers={ 'Content-Type': 'application/x-www-form-urlencoded' }) else: self.response.out.write('No Seed User') except Exception: logging.error('admin.SyncToProd', exc_info=True) logging.info("Sync Done to Prod") self.response.out.write("OK")
def test_update_order__failure_availability(self, mocker): mocker.patch('views.orders.database', new=self.TEST_DB) user = add_user('*****@*****.**', TEST_USER_PSW, id='90c3e1c1-b51c-4224-b69d-17f84f6a8dfc') addr = add_address(user=user, id='8f3b518e-9c17-4103-9a47-b274740726e7') item = Item.create( uuid='429994bf-784e-47cc-a823-e0c394b823e8', name='mario', price=20.20, description='svariati mariii', availability=4, category='scarpe', ) order = Order.create( delivery_address=addr, user=user, ).add_item(item, 2) update_order = { 'relationships': { 'items': [{ 'id': '429994bf-784e-47cc-a823-e0c394b823e8', 'type': 'item', 'quantity': 5 }] } } post_data = format_jsonapi_request('order', update_order) path = 'orders/{}'.format(order.uuid) resp = open_with_auth(self.app, API_ENDPOINT.format(path), 'PATCH', '*****@*****.**', TEST_USER_PSW, 'application/json', json.dumps(post_data)) assert resp.status_code == BAD_REQUEST assert OrderItem.select().count() == 1 assert OrderItem.get() == order.order_items[0] assert order.order_items[0].quantity == 2