def save(self, request): "Process form and create DB objects as required" if self.instance: item = self.instance else: item = Item() item.item_type = self.item_type item.name = unicode(self.cleaned_data['name']) item.parent = self.cleaned_data['parent'] item.status = self.cleaned_data['status'] item.manufacturer = self.cleaned_data['manufacturer'] item.supplier = self.cleaned_data['supplier'] item.owner = self.cleaned_data['owner'] item.location = self.cleaned_data['location'] item.asset = self.cleaned_data['asset'] if not item.id: item.set_user_from_request(request) item.save() if self.instance: item.itemvalue_set.all().delete() for field in item.item_type.fields.all(): for form_name in self.cleaned_data: if re.match(str("^" + field.name + "___\d+$"), form_name): value = None if isinstance(self.fields[form_name], forms.FileField): value = ItemValue( field=field, item=item, value=self._handle_uploaded_file(form_name)) if isinstance(self.fields[form_name], forms.ImageField): self._image_resize(value.value) else: if field.field_type == 'picture' and isinstance(self.fields[form_name], forms.ChoiceField) and\ self.cleaned_data[form_name] != 'delete': value = ItemValue( field=field, item=item, value=self.cleaned_data[form_name]) else: value = ItemValue( field=field, item=item, value=self.cleaned_data[form_name]) if value: if not value.value: value.value = '' value.save() return item
def createItem(name, description, category_id, user_id): """ Create an item """ item = Item(name=name, description=description, edited_on=datetime.today(), category_id=category_id, user_id=user_id) if item: session.add(item) session.commit() return item return None
def itemsadd(): if request.method == 'POST': name = request.form['name'] price = int(request.form['price']) image = request.files['image'] fname = image.filename image.save(os.path.join(basedir + r'item\\' + fname)) i = Item(name=name, price=price, image=fname, seller=current_user) db.session.add(i) db.session.commit() return render_template('itemsadd.html') return render_template('itemsadd.html')
def run_random(parallel=False): types_count = int(input("Задайте количество различных типов предметов: ")) items = [ Item(i, random.randint(1, 20), random.randint(1, 20)) for i in range(types_count) ] max_volume = int(input("Введите объем рюкзака: ")) if parallel: estimator = BackpackFactoryParallelLauncher(items, max_volume) else: estimator = BackpackFactory(items, max_volume) return estimator
def test_get_an_item(self): """ Get an Item by id """ toothbrush = Item(wishlist_id=1, product_id=2, name="toothbrush", description="I need one") toothbrush.save() item = Item.get(toothbrush.id) self.assertEqual(item.id, toothbrush.id) self.assertEqual(item.name, "toothbrush")
def addItem(cat): category = session.query(Category).filter_by(name=cat).one() if request.method == 'POST': newItem = Item(name=request.form['name'], description=request.form['description'], category=category) session.add(newItem) flash('%s created' % newItem.name) session.commit() return redirect(url_for('showItems', cat=category.name)) else: return render_template('additem.html', category=category)
def test_delete_an_item(self): """ Delete an Item """ item = Item(order_id=1, product_id=1, name="wrench", quantity=1, price=10.50) item.save() self.assertEqual(len(Item.all()), 1) item.delete() self.assertEqual(len(Item.all()), 0)
def new_item(category_id): """ Route that renders the page to add a new item. This method validate that the user is logged in. The item is associated with the current logged in user. Args: category_id: The id of the category of the item to be added. Raises: If an error occurs the application will redirect to index page and a flash message will be displayed with the proper Exception message. """ try: logged_in = 'username' in login_session if not logged_in: flash("You must be logged to perform this operation", category="error") return redirect(url_for('index')) form = ItemForm() item = Item() item.name = "New item" if form.validate_on_submit(): form.populate_obj(item) item.user_id = login_session["user_id"] db_session.add(item) if len(secure_filename(form.photo.data.filename)) > 0: db_session.flush() filename = 'images/uploads/' + str(item.id) + '/' + \ secure_filename(form.photo.data.filename) ensure_dir('static/' + filename) form.photo.data.save('static/' + filename) item.image_path = filename db_session.add(item) db_session.commit() flash("Item '{}' successfully added".format(item.name)) return redirect( url_for('get_item_by_category', category_id=item.category_id, item_id=item.id)) else: categories = db_session.query(Category).order_by( Category.name).all() return render_template('new_item.html', categories=categories, active_category=int(category_id), item=item, form=form, logged_in=logged_in, login_session=login_session) except Exception as e: flash('An error has occurred: {}'.format(str(e)), 'error') return redirect(url_for('index'))
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 bootstrap_data(): """Bootstraps the database""" db.drop_all() db.create_all() steven = User(username="******", password="******", name="Steven Milov") db.session.add(steven) bs1 = Item(name="Itchy", description="Gets that itchy itch out!", size="XL", price="$19.99") bs2 = Item(name="Scratchy", description="Gets that scratchy itch out!", size="S", price="$24.99") db.session.add(bs1) db.session.add(bs2) db.session.commit() print('Bootstrapped the database.')
def parser(uri: ParseResult) -> List[Item]: """Парсер стен ВКонтакте""" domain = uri.path.strip('/') api = VkAPI() response = api.wall_get(domain=domain) return [ Item(link=f"https://vk.com/wall{i['owner_id']}_{i['id']}", title=f"#{i['id']}", description=i['text'].replace('\n', '<br>'), pub_date=datetime.fromtimestamp(i['date'])) for i in response['items'] ]
def offer_create(): """ Handles the creation of new Items. Items are shown as car offers for the public. Methods: GET: If a GET request is made, the offer_create.html template with a form is rendered. POST: A POST request usually happens on form submit and finally creates a new Item object. Returns: GET method: offer_create.html with a form to execute a POST request. POST method: Redirects to homepage with a message in case of success. """ if flask.request.method == 'POST': name = request.form['item_name'] description = request.form['item_description'] category = request.form['item_category'] price = request.form['item_price'] photo = request.files['item_photo'] year = request.form['item_year'] fuel = request.form['item_fuel'] consumption = request.form['item_consumption'] color = request.form['item_color'] miles = request.form['item_miles'] user = login_session['gplus_id'] filename = secure_filename(photo.filename) photo.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) item = Item(name=name, description=description, category=category, price=price, photo=filename, year=year, fuel=fuel, consumption=consumption, color=color, miles=miles, user=user) db.session.add(item) db.session.commit() flash('Added your offer successfully', 'success') return redirect('/') else: categories = Category.query return render_template('offer_create.html', categories=categories)
def newItem(name, description, categoryName): try: category = showCategory(categoryName) new_item = Item(name=name, description=description, category=category, user=getCurrentUser()) session.add(new_item) session.commit() return True except: return False
def addItem(name, category_name, description, username): session = createDBSession() if session.query(Item).filter_by(name=name).first() is not None: return "This item already exists!" else: user = session.query(User).filter_by(username=username).first() category = session.query(Category).filter_by(name=category_name).first() newItem = Item(name=name, category_id=category.id, description=description, owner_id=user.id) session.add(newItem) session.commit() category = session.query(Category).filter_by(id=category.id).first() print("Created {itemName} under the {categoryName} category!".format(itemName=name, categoryName=category.name))
def post(self): print( f"**************** Create custom item: {session.get('user_id')} and {session.items()} **********" ) submitted_title = json.loads(request.data) item = Item(i_title=submitted_title['i_title'], i_dt_created=datetime.now(), u_id=session["user_id"]) db.session.add(item) db.session.commit() print(jsonify(item.serialize())) return jsonify(item.serialize())
def getCatalog(): items = session.query(Item).all() #Populate an empty database if items == []: item1 = Item( name="Pineapple", price="$2.50", picture= "https://upload.wikimedia.org/wikipedia/commons/c/cb/Pineapple_and_cross_section.jpg", description="Organically Grown in Hawai'i") session.add(item1) item2 = Item( name="Carrots", price="$1.99", picture= "http://media.mercola.com/assets/images/food-facts/carrot-fb.jpg", description="High in Vitamin A") session.add(item2) item3 = Item(name="Aluminum Foil", price="$3.50", picture="http://images.wisegeek.com/aluminum-foil.jpg", description="300 feet long") session.add(item3) item4 = Item( name="Eggs", price="$2.00", picture= "http://whatsyourdeal.com/grocery-coupons/wp-content/uploads/2015/01/eggs.png", description="Farm Fresh Organic Eggs") session.add(item4) item5 = Item( name="Bananas", price="$2.15", picture="http://dreamatico.com/data_images/banana/banana-3.jpg", description="Fresh, delicious, and full of potassium") session.add(item5) session.commit() items = session.query(Item).all() return jsonify(catalog=[i.serialize for i in items])
def item(id=None): if request.method == 'GET': if id is not None: item = Item.query.get(id) if item: return jsonify(item.serialize()), 200 else: return jsonify({"msg":"item not found"}), 404 else: item = Item.query.all() item = list(map(lambda item: item.serialize(), item)) return jsonify(item), 200 if request.method == 'POST': nombre = request.json.get('nombre', None) descripcion = request.json.get('descripcion', None) if not nombre: return jsonify({"msg":"name is required"}), 422 if not descripcion: return jsonify({"msg":"description is required"}), 422 item = Item() item.nombre = nombre item.descripcion = descripcion db.session.add(item) db.session.commit() return jsonify(item.serialize()), 201 if request.method == 'PUT': nombre = request.json.get('nombre', None) descripcion = request.json.get('descripcion', None) if not nombre: return jsonify({"msg":"name is required"}), 422 if not descripcion: return jsonify({"msg":"description is required"}), 422 item = Item.query.get(id) if not item: return jsonify({"msg":"item not found"}), 404 item.nombre = nombre item.descripcion = descripcion db.session.commit() return jsonify(item.serialize()), 200 if request.method == 'DELETE': item = Item.query.get(id) if not item: return jsonify({"msg":"item not found"}), 404 db.session.delete(item) db.session.commit() return jsonify({"msg":"item deleted"}), 200
def test_get_an_item(self): """ Get an Item by id """ hammer = Item(order_id=1, product_id=2, name="hammer", quantity=2, price=11) hammer.save() item = Item.get(hammer.id) self.assertEqual(item.id, hammer.id) self.assertEqual(item.name, "hammer")
def post(self, r, e): d = r.get("description", None) if d is None: self.response.status = 400 self.response.headers['Content-Type'] = 'application/json' self.response.write( json.dumps({"error": "Request missing description field"})) return i = Item(description=d, owner=e) k = i.put() self.response.status = 200 self.response.headers['Content-Type'] = 'application/json' self.response.write(json.dumps({"id": str(k.id())}))
def _create_item_in_database(self, cart, product, quantity=1, unit_price=Decimal("100")): """ Helper function so I don't repeat myself """ item = Item() item.cart = cart item.product = product item.quantity = quantity item.unit_price = unit_price item.save() return item
def add_item_to_db(dataset, item): count = db.session.query( Dataset, Dataset.name).filter(Dataset.name == dataset).all() if len(count) == 0: return None testitem = Item(dataset_name=dataset, item=str(item), status='available', timestamp=datetime.now()) db.session.add(testitem) db.session.commit() return 'added'
def add_item(category_id): form = Itemform() form.cat_id.choices = [(cat.id, cat.name) for cat in Category.query.all()] if form.validate_on_submit(): item_new = Item(cat_id=form.data.get('cat_id'), description=form.data.get('description'), title=form.data.get('title')) db_session.add(item_new) db_session.commit() return redirect('/category/{}'.format(category_id)) return render_template("add_item.html", form=form)
def scrape_links(): url = 'https://www.bbc.co.uk/news/topics/cm8m1391ddrt/news-daily' response = http_get.simple_get(url) if response is not None: html = BeautifulSoup(response, 'html.parser') for link in html.select('a.qa-heading-link'): m = re.match(r"^/news/uk-([\w]+)\?intlink", link['href']) item = Item( m.group(1), link.find('span').text, "https://www.bbc.co.uk{href}".format(href=link['href']), datetime.datetime.now().strftime("%a, %d %b %Y %H:%M:%S %z")) yield item
def newitem(categoria_id): if current_user.is_authenticated and request.method == 'POST': item = Item(name=request.form['name'], description=request.form['desc'], categoria_id=categoria_id) session.add(item) session.commit() return redirect(url_for('itenscategoria', categoria_id=categoria_id)) return render_template( 'newitem.html', categoria=session.query(Categoria).filter_by(id=categoria_id), loggeduser=current_user.name)
def newItem(category_id): if request.method == 'POST': newItem = Item(title=request.form['title'], description=request.form['description'], category_id=category_id) session.add(newItem) session.commit() flash("New Item Created") return redirect(url_for('showItems', category_id=category_id)) else: return render_template('newItem.html', category_id=category_id) return render_template('newMenuItem.html', category=category)
def test_add_item_description(self): """ Add an item description to an item """ item = Item(wishlist_id=2, product_id=4, name='soda').save() item = Item.find_by_name('soda')[0] new_item = {'description': 'I need some soda'} data = json.dumps(new_item) resp = self.app.post('/items/{}/description'.format(item.id), data=data, content_type='application/json') self.assertEqual(resp.status_code, status.HTTP_201_CREATED) # Check the data is correct new_json = json.loads(resp.data) self.assertEqual(new_json['description'], 'I need some soda')
def create_item(item_request: AddItemRequest, username: str = Depends(get_current_user), db: Session = Depends(get_db)): item = Item() item.Name = item_request.Name item.Score = item_request.Score item.Value = item_request.Value item.owner_id = username.id db.add(item) db.commit() return {"code": "success", "message": "item added"}
def add_item_post(self, request): check_signed_in() try: item = Item(title=request.title, description=request.description, expiration=datetime.strptime(request.expiration, "%m/%d/%Y"), price=request.price, owner=User.get_current_user()) key = item.put() return BaseMessage(message="OK", code="OK", data=str(key.id())) except BadValueError as e: return BaseMessage(message=e.message, code="ERROR", data=e.message)
def long_task(id): time.sleep(10) items=Item.query.filter_by(user_id=id) items_to_add=[] for item in items: temp=Item( user_id=item.user_id, name=item.name, description=item.description ) items_to_add.append(temp) db.session.bulk_save_objects(items_to_add) db.session.commit()
def add_item(user_id, song_id, playlist_id): new_item = Item(song_id=song_id, playlist_id=playlist_id) user = User.query.filter_by(id=user_id).first_or_404( description="No such user found.") my_playlist = Playlist.query.filter_by(id=user.playlist_id).first() if not exists(new_item, my_playlist.items): song = Song.query.get(song_id) db.session.add(new_item) song.n += 1 db.session.commit() # using db session add the new item # increase the counter for the song associated with the new item return redirect(url_for('profile', user_id=user_id))