def manage_categoryitem(categoryitem_id=None, type_op=1): """ Manage category item CRUD Args: param1: category item id param2: operation type (1 -> read, 2 -> new, 3 -> update, 4 -> delete) """ item = CategoryItem.by_id(categoryitem_id) if item is None and type_op != 2: flash(_('no_found_rows')) if type_op == 4: db.session.delete(item) db.session.commit() flash(_('item_deleted_successfully')) return redirect(url_for('show_categories')) form = CategoryItemForm(request.form) form.category_id.choices = [(c.id, c.name) for c in Category.query.all()] form.brand_id.choices = [(b.id, b.name) for b in Brand.query.all()] if item is not None and request.method == 'GET': form.name.data = item.name form.description.data = item.description form.price.data = item.price form.category_id.data = item.category_id form.brand_id.data = item.brand_id if request.method == 'POST' and form.validate(): if categoryitem_id is not None: item.name = form.name.data item.description = form.description.data item.price = form.price.data item.category = Category.get_by_id(id=form.category_id.data) item.brand = Brand.get_by_id(id=form.brand_id.data) item.user = User.get_by_id(login_session['user_id']) flash(_('item_updated_successfully')) else: item = CategoryItem( name=form.name.data, description=form.description.data, price=form.price.data, category=Category.get_by_id(id=form.category_id.data), # noqa brand=Brand.get_by_id(id=form.brand_id.data), # noqa user=User.get_by_id(login_session['user_id'])) # noqa flash(_('item_added_successfully')) db.session.add(item) db.session.commit() return redirect( url_for('show_categoryitem_read', categoryitem_id=item.id)) # noqa return render_template('categoryitem.html', item=item, type_op=type_op, form=form)
def new_brand(): form = NewBrandForm() if form.validate_on_submit(): brand = Brand() brand.name = form.name.data brand.code = form.code.data db.session.add(brand) db.session.commit() return redirect(url_for('brand_report')) return render_template('brand/add.html', title='Add new brand', form=form)
def seed_brands(): brand1 = Brand(brand="Discraft") brand2 = Brand(brand="Innova") brand3 = Brand(brand="Dynamic Discs") db.session.add(brand1) db.session.add(brand2) db.session.add(brand3) db.session.commit()
def setUp(self): app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///" + os.path.join( basedir, "test.db") self.app = app.test_client() self.app_context = app.app_context() self.app_context.push() db.create_all() brand1 = Brand(carSeries="Lambo") brand2 = Brand(carSeries="AS") brand3 = Brand(carSeries="GTR") db.session.add(brand1) db.session.add(brand2) db.session.add(brand3) db.session.commit()
def create_brand(): form = BrandForm() if form.validate_on_submit(): master_uid = Master.master_uid() current_site = Site.query.filter_by(master_uid=master_uid).first() brand = Brand(master_uid=master_uid, site_id=current_site.id, name=form.name.data, features=form.features.data, description=form.description.data, sort_num=form.sort_num.data, logo_id=form.logo.data, banner_id=form.banner.data) db.session.add(brand) db.session.commit() flash('Add brand is ok!', 'success') return redirect(url_for('.show_brands')) mode = 'create' brand = None return render_template('admin/brands/submit.html', form=form, brand=brand, mode=mode)
def add(tasting_id): form = ReviewForm(tasting_id=tasting_id) current_time = datetime.utcnow() if form.validate_on_submit(): filename = secure_filename(form.image.data.filename) # set age to 0 if it has not been entered if form.age.data == "": age = 0 else: age = int(form.age.data) if form.brand_id.data is '0': brand = Brand(name=form.brand_name.data) db.session.add(brand) db.session.flush() review = Review(order=form.order.data, notes=form.notes.data, tasting_note=form.tasting_note.data, img_name=filename, name=form.name.data, age=age, max_rating=form.max_rating.data, avg_rating=form.avg_rating.data, min_rating=form.min_rating.data, author=current_user, brand_id=brand.id, tasting_id=form.tasting_id.data) else: review = Review(order=form.order.data, notes=form.notes.data, tasting_note=form.tasting_note.data, img_name=filename, name=form.name.data, age=form.age.data, max_rating=form.max_rating.data, avg_rating=form.avg_rating.data, min_rating=form.min_rating.data, author=current_user, brand_id=form.brand_id.data, tasting_id=form.tasting_id.data) db.session.add(review) db.session.commit() pathlib.Path(current_app.config['UPLOAD_FOLDER'] + '/' + str(review.id)).mkdir(parents=True, exist_ok=True) form.image.data.save(current_app.config['UPLOAD_FOLDER'] + '/' + str(review.id) + '/' + filename) rotateImage( current_app.config['UPLOAD_FOLDER'] + '/' + str(review.id) + '/', filename) flash('Your review is now live!') return redirect( url_for('main.tasting', tasting_id=form.tasting_id.data)) return render_template( 'add_review.html', title='Add Review', form=form, )
def parse_item(self, item, index, package_type): ''' Parses an individual entry from the main listing. This is how the majority of the updates will be occuring. We will mostly be using these updates for awareness of auctions that have been added. While we are here we will continue to track the price of the auction even though it is not closed, as this may become relevent in some searches. ''' aid = item.findChild('input', {'name': 'frmAuctionID%s' % index}).get('value') bid = item.findChild('input', {'name': 'frmBrandCode%s' % index}).get('value') auction = Auction.query.filter_by(aid=aid, site='cigarauctioneer').first() brand = Brand.query.filter_by(ca_id=bid).first() if not brand: brand = Brand() brand.name = item.findChild('input', {'name': 'frmBrandDesc%s' % index}).get('value') brand.ca_id = bid db.session.add(brand) if not auction: # as we haven't seen this action before, we will need to get all of # the usual information and store that into a new Auction database # object. auction = Auction() auction.type = package_type auction.name = item.findChild('input', {'name': 'frmItemDesc%s' % index}).get('value') auction.aid = aid auction.site = 'cigarauctioneer' auction.close = self.timestamp_gen(item.findChild('div', text='Time Left:').findNext('div').text) auction.link = item.findChild('a', {'itemprop': 'url'}).get('href') if package_type is not 'singles': auction.quantity = int(item.findChild('input', {'name': 'frmItemsPerPack%s' % index}).get('value')) else: auction.quantity = 1 brand.auctions.append(auction) db.session.add(auction) # now we need to get the current price and update the timestamp. auction.price = float(item.findChild('div', {'itemprop': 'price'}).text.strip('$')) auction.timestamp = datetime.now() # Now we need to commit the changes to the database ;) db.session.commit()
def get(self): self.response.headers['Content-Type'] = 'text/plain' sale_ids = [] brands = defaultdict(dict) content = helper.fetch('http://m.gilt.com/pagegen_service/sale/mobile_sale_set') if content: sale_groups = json.loads(content).get('data').get('mobile_sale_set').get('sale_groups') active_sales = [sale_group.get('sales') for sale_group in sale_groups if sale_group.get('title') == 'Active Sales'][0] for sale_data in active_sales: sale_id = sale_data.get('id') sale_name = sale_data.get('name') sale_data['stores'] = [str(store.lower()) for store in sale_data['stores']] sale = Sale.create(sale_data) if sale: new_sale_msg = "Created sale %s - %s.\nhttp://%s/tasks/fetch/sale/%d\n\n" % \ (sale_id, sale_name, self.request.host, sale_id) else: new_sale_msg = "Sale %s - %s already exists.\n\n" % (sale_id, sale_name) self.response.out.write(new_sale_msg) sale_ids.append(sale_id) for brand in sale_data.get('brands') or []: Brand.create(brand_id=brand.get('id'), name=brand.get('name')) for sale_id in sale_ids: task_name = TASK_NAME_FETCH_SALE % (TASK_QUEUE_FETCH_SALE, sale_id, datetime.now().microsecond) task = taskqueue.Task(url='/tasks/fetch/sale/%s' % (sale_id), \ params={'brands': brands[sale_id]}, name=task_name, method='GET') try: task.add(TASK_QUEUE_FETCH_SALE) task_msg = "Added task '%s' to task queue '%s'.\n" except TaskAlreadyExistsError: task_msg = "Task '%s' already exists in task queue '%s'.\n" except TombstonedTaskError: task_msg = "Task '%s' is tombstoned in task queue '%s'.\n" self.response.out.write("%s\n%s" % (task.url, task_msg % (task.name, TASK_QUEUE_FETCH_SALE)))
def test_news_json(self): brand = Brand(name='fake-name', slug='fake-slug', tagline='fake-tagline', text='fake-text',) brand.save() response = self.client.get('/ajax/brands/') self.assertEqual(response.status_code, 200) self.assertContains(response, 'fake-name') self.assertContains(response, 'fake-slug') self.assertContains(response, 'fake-tagline') self.assertContains(response, 'fake-text') product = Product(name='fake-product-name', slug='fake-product-slug', text='fake-product-text',) product.save() brand.products.add(product) brand.save() response = self.client.get('/ajax/brands/') self.assertEqual(response.status_code, 200) self.assertContains(response, 'fake-product-name')
def addVote(): if request.method == "POST": result = request.form carname = result['text'] addCar = Brand(carSeries=carname) db.session.add(addCar) db.session.commit() flash("car added successfully: " + str(carname)) return redirect(url_for('hoster'))
def edit_review(review_id): review = Review.query.filter_by(id=review_id).first() form = ReviewForm(obj=review) if review.brand is not None: form.brand_name.data = review.brand.name if form.validate_on_submit: if request.method == 'POST': if form.age.data == "": age = 0 else: age = int(form.age.data) if form.brand_id.data is '0': brand = Brand(name=form.brand_name.data) db.session.add(brand) db.session.flush() review.brand_id = brand.id else: review.brand_id = form.brand_id.data review.order = form.order.data review.notes = form.notes.data review.tasting_note = form.tasting_note.data review.name = form.name.data review.age = age review.max_rating = form.max_rating.data review.avg_rating = form.avg_rating.data review.min_rating = form.min_rating.data review.author = current_user if form.image.data is not None: filename = secure_filename(form.image.data.filename) pathlib.Path(current_app.config['UPLOAD_FOLDER'] + '/' + str(review.id)).mkdir(parents=True, exist_ok=True) form.image.data.save(current_app.config['UPLOAD_FOLDER'] + '/' + str(review.id) + '/' + filename) review.img_name = filename rotateImage( current_app.config['UPLOAD_FOLDER'] + '/' + str(review.id) + '/', filename) db.session.commit() flash('Your changes have been saved.') return redirect( url_for('main.tasting', tasting_id=review.tasting.id)) return render_template('add_review.html', title='Edit Review', action="Edit", form=form)
def insert_brand_product_relations(bname, brand_dict): brand = Brand(bname, float(format(brand_dict['avg_price'], '.2f')), float(format(brand_dict['avg_rating'], '.2f')), len(brand_dict['products']), brand_dict['image_url']) db.session.add(brand) db.session.flush() for prod in brand_dict['products']: cur_product = PRODUCTS[prod] product = Product(brand.id, cur_product['name'], cur_product['description'], float(format(cur_product['price'], '.2f')), float(format(cur_product['rating'], '.2f')), cur_product['image_url']) db.session.add(product) db.session.flush() # Add product_tag relation for tag in cur_product['tags']: product.tags.append( Tag.query.filter_by(name=get_tag_name(tag)).first()) # Add product_color relation for color in cur_product['colors']: product.colors.append( Color.query.filter_by(name=color['colour_name']).first()) # Add product_category relation cid = cur_product['category'] sid = None if 'sub_category' in cur_product: sid = cur_product['sub_category'] product_category = ProductCategory(product.id, get_category_id(cid), get_sub_category_id(sid)) db.session.add(product_category) brand.products.append(product) db.session.commit()
def insert_a_brand(): brand_name = request.args.get("brand_name") brand_pic_url = request.args.get("brand_pic_url") brand_cate_id = request.args.get("brand_cate_id") brand_note = request.args.get("brand_note") if brand_name is None: return CommonError.args_miss(msg='brand_name_required') if brand_pic_url is None: return CommonError.args_miss(msg='brand_pic_url_require') if brand_cate_id is None: return CommonError.args_miss(msg='brand_cate_id_required') if brand_note is None: return CommonError.args_miss(msg='brand_note_required') brand = Brand() brand.brand_name = brand_name brand.brand_pic_url = brand_pic_url brand.brand_cate_id = brand_cate_id brand.brand_note = brand_note db.session.add(brand) db.session.commit() return responseSuccessHandler(body={'brand_id': brand.brand_id})
def get(self, sale_id): self.response.headers['Content-Type'] = 'text/plain' sale_id = int(sale_id) sale = Sale.lookup(sale_id) if not sale: self.response.out.write('Sale id %d not found.\n' % (sale_id)) else: url = "%s/sale/mobile_sale_listing?sale_id=%d" % (API_SVC, sale_id) content = helper.fetch(url) products_data = json.loads(content)['data']['products'] if products_data and len(products_data): brand_entities = [Brand.get_by_key_name(str(product['brand_id'])) for product in products_data.values()] brands = dict([(int(brand.id), brand) for brand in brand_entities if brand]) for product_id, product_data in products_data.items(): brand_id = product_data['brand_id'] brand = Brand.lookup(brand_id) product_id = int(product_id) product_data['name'] = mod_product_string(product_data['name']) product_data['description'] = mod_product_string(product_data['description'], '\n') product_data['categories'] = list(itertools.chain(*([k.split('_') for k in product_data['category_keys']]))) product = Product.create(product_id, product_data, sale, brands.get(brand_id) or Brand.create(brand_id)) if not product: self.response.out.write("Did not create product %d - %s.\n" % (product_id, product_data['name'])) else: self.response.out.write("Created product %d - %s.\n" % (product_id, product_data['name'])) prices = [] sizes = [] looks = product_data['looks'] if looks: for look_data in looks: look_id = look_data['look_id'] look = Look.create(look_id, look_data, product) if not look: self.response.out.write('\tDid not create Look for look id %d.\n' % look_id) else: self.response.out.write('\tCreated look id %d for product %d %s.\n' % (look_id, product_id, product.name)) prices.extend([look_data.get(price_key) for price_key in PRICE_KEYS]) skus = look_data.get('skus') or [] for sku_data in skus: size = sku_data.get('size') if size: if size[0].isdigit(): sizes.extend(size.split('/')) else: sizes.append(size) sku_id = sku_data['sku_id'] sku = SKU.create(sku_id, sku_data, look or Look.get_by_key_name("%s" % look_id)) if sku: self.response.out.write('\t\t- Created SKU %d.\n' % sku_id) prices.extend([sku_data.get(price_key) for price_key in PRICE_KEYS]) else: self.response.out.write('\t\t- Did not create SKU %d.\n' % sku_id) prices = list(frozenset(filter(lambda price: price and price > 0, prices))) if prices: product.lowest_price = min(prices) product.highest_price = max(prices) if sizes: product.sizes = list(frozenset(sizes)) product.put() self.response.out.write("\n\n")
def addProduct(): """ Add Product The add product route takes a ZINC api product ID and adds said product to the database with all connections nessesery Post example: ``` { 'retailer': 'aliexpress', # Only recommended for now 'product_id': '32850545097' # some random bag } ``` The code here is an antipattern """ try: # Grab the post request data = request.get_json() # grab the item from the API per the POST data = http.get(f"{zinc}/products/{data['product_id']}", params=[('retailer', data['retailer'])], auth=(api_key, '')) data = data.json() # Create base item class item = Item( product_id=data['product_id'], title=data['title'], desc=data['product_description'], old_price=data['price'], new_price=(int(data['price']) * 1.4), ) # Makes the new categories # TODO: check for existing categories = [Category(title=x) for x in data['categories']] # Querys for the brand brand = Brand.query.filter_by(title=data['brand']).first() # Creates new brand if not existant in local db brand = brand if brand else Brand(title=data['brand']) # Commits the items to the db db.session.add_all([ item, brand, *categories, Brand_Item(item_id=item.id, brand_id=brand.id), # dynamically uses list comprehention to generate list of # classes and then unwraps them into function as individuals # This is done multiple times for a number of tables *[ Bullets(item_id=item.id, text=x) for x in data['feature_bullets'] ], *[ Image( item_id=item.id, img_url=x, is_primary=False if index != 0 else True, ) for index, x in enumerate(data['images']) ], *[ Category_Item(item_id=item.id, category_id=x.id) for x in categories ], *[Details(item_id=item.id, text=x) for x in data['details']] ]) # Commits to the db db.session.commit() return "Success", 200 except: return "Invalid json format", 400
#!/usr/bin/env python from app import db from app.models import User, Category, CategoryItem, Brand db.create_all() # Brands brand1 = Brand(name="Nike") brand2 = Brand(name="Adidas") brand3 = Brand(name="Wilson") db.session.add(brand1) db.session.add(brand2) db.session.add(brand3) db.session.commit() # Categories category1 = Category(name="Soccer") category2 = Category(name="Basketball") category3 = Category(name="Baseball") category4 = Category(name="Frisbee") category5 = Category(name="Snowboarding") category6 = Category(name="Rock Climbing") category7 = Category(name="Foosball") category8 = Category(name="Skating") category9 = Category(name="Hockey") db.session.add(category1) db.session.add(category2) db.session.add(category3) db.session.add(category4) db.session.add(category5)
def get_brands(): page = request.args.get('page', 1, type=int) per_page = min(request.args.get('per_page', 10, type=int), 100) data = Brand.to_collection_dict(Brand.query, page, per_page, 'api.get_brands') return jsonify(data)
def brandsautocomplete(): query = request.args.get('q', '') data = Brand.to_collection_dict_all( Brand.query.filter(Brand.name.like("%" + query + "%"))) return jsonify(data)