def productView(request): product = None categories = Categories.get_all_categories() categoryId = request.GET.get("category") if categoryId: categoryId = int(categoryId) product = Products.get_all_products_by_id(categoryId) else: categoryId = int(categories[0].id) product = Products.get_all_products_by_id(categoryId) dataJSON = serializers.serialize('json', product) specialItems = SpecialItems.get_all_items() cardJSONData = serializers.serialize('json', specialItems) return render( request, "products.html", { "products": product, "jsonProducts": dataJSON, "categories": categories, "selectedCategoryId": categoryId, "specialCardItems": cardJSONData, }, )
def create_product(): data = request.get_json() or {} if 'product_name' not in data: return bad_request('must include product_name fields') if Products.query.filter_by(product_name=data['product_name']).first(): return bad_request('please use a different product_name') product = Products() product.from_dict(data, new_product=True) db.session.add(product) db.session.commit() response = jsonify(product.to_dict()) response.status_code = 201 response.headers['Location'] = url_for('api.get_products', id=product.product_id) return response
def upload(request): myfile = request.FILES['file'] with open('products.csv', 'wb+') as destination: for chunk in myfile.chunks(): destination.write(chunk) data = pd.read_csv('products.csv', chunksize=1000000) chunk_list = [] for chunk in data: chunk_list.append(chunk) df_concat = pd.concat(chunk_list) stats = ['active', 'inactive'] df_concat = df_concat.drop_duplicates(subset='sku', keep="last") df_records = df_concat.to_dict('records') model_instances = [Products( sku=record['sku'], description=record['description'], name=record['name'], status=random.choice(stats) ) for record in df_records] Products.objects.bulk_create(model_instances) return render(request, "upload.html")
def update(): prices_data = json.load(open("json_data/prices.json")) for price in prices_data["prices"]: p = Products(id=price["product_id"], price=price["price"], vat_band=price["vat_band"]) db.session.add(p) for name, rate in prices_data["vat_bands"].items(): v = VatRates(name=name, rate=rate) db.session.add(v) country_codes = json.load( open("json_data/country_code.json", errors="ignore")).keys() for code in country_codes: e = ExchangeRates(country_code=code, exchange_rate=None) db.session.add(e) api_keys = json.load(open("json_data/api_keys.json")) for api in api_keys: api = ApiKeys(name=api["name"], api_key=api["api_key"], url=api["url"]) db.session.add(api) db.session.commit()
def submit(): if request.method == "POST": #This is for adding the deals with the button in there if "submit_for_deal" in request.form: deal_type = request.form["deal_type"] deal_products = request.form["products_for_deal"] current_deal = Deals.query.filter_by(deal_type=deal_type).first() if deal_products == "": return redirect(url_for("index")) if current_deal is not None: current_deal.deal_items += f', {deal_products}' db.session.commit() return redirect(url_for("index")) else: data = Deals(deal_type, deal_products) db.session.add(data) db.session.commit() return redirect(url_for("index")) product = request.form["product"] price = request.form["price"] if product == "" and price == "": return redirect(url_for("index")) #If we do not have the submit_for_deal input then we add product #This way we keep both the submits in one single route data = Products(product, price) db.session.add(data) db.session.commit() return redirect(url_for("index"))
def product_create(): form = ProductForm(current_user.username) if not os.path.exists(path): os.makedirs(path) if form.validate_on_submit(): filenames = secure_filename(form.filename_images.data.filename) ext = filenames.split(".")[-1] filenames = "%s.%s" % (uuid.uuid4().hex, ext) destination_save = "/".join([path, filenames]) form.filename_images.data.save(destination_save) products = Products(title=form.title.data, price=form.price.data, filename_images=filenames, file=form.file.data.read(), file_filename=form.file.data.filename, content=form.content.data, kategori_id=form.category.data.id) db.session.add(products) db.session.commit() flash('Product has been created.', 'success') return redirect(url_for("admin.product_lihat")) return render_template("product_create.html", title="Tambah Data", form=form)
def place_order(): form = OrderForm() engineer_id = request.args.get('engineer_id', 0, type=int) if form.validate_on_submit(): order = Order(title=form.title.data, description=form.description.data, working_hours=form.working_hours.data, state_id=Code.wait, begin_time=form.begin_time.data, project=Project.query.get(form.project.data), sales=current_user) if engineer_id == 0: if not order.polling(): flash('该工单入场时间段内无可用工程师') db.session.rollback() return redirect('sales.index') else: order.engineer = User.query.get(engineer_id) db.session.add(order) for i in request.form.getlist('products'): p = Products(order=order, product=Product.query.get(int(i))) db.session.add(p) db.session.commit() flash('已将工单派发给工程师{}'.format(order.engineer.name)) return redirect(url_for('sales.orders')) if engineer_id != 0: user = User.query.get(engineer_id) form.engineer.choices = [(user.id, user.name)] return render_template('sales/place_order.html', title='派工', form=form)
def add_product(): form = AddProductsForm() if form.validate_on_submit(): image_folder = strftime("%Y-%m-%d-%H-%M-%S", gmtime()) if 'photo' not in request.files: return redirect(url_for('add_product')) photos = request.files.getlist('photo') profile_photo = request.files['profile_photo'] if not os.path.exists(os.path.join(app.config['UPLOAD_FOLDER'], image_folder)): os.makedirs(os.path.join(app.config['UPLOAD_FOLDER'], image_folder)) else: return redirect(url_for('add_product')) count = 2; for photo in photos: if photo.filename == '': flash('No selected image') return redirect(url_for('add_product')) if photo and allowed_file(photo.filename): filename = secure_filename(str(count)+'.'+photo.filename.rsplit('.', 1)[1].lower()) count += 1; photo.save(os.path.join(app.config['UPLOAD_FOLDER'], image_folder, filename)) profile_photo_filename = secure_filename('1.'+profile_photo.filename.rsplit('.', 1)[1].lower()) profile_photo.save(os.path.join(app.config['UPLOAD_FOLDER'], image_folder, profile_photo_filename)) profile_location = image_folder+'/'+profile_photo_filename product = Products(product_name=form.productname.data, price=form.price.data, detail_information=form.detail_information.data, category=form.category.data, photo = image_folder, profile_photo = profile_location) db.session.add(product) db.session.commit() return redirect(url_for('add_product')) return render_template('add_product.html', title='Add Product', form=form)
async def get_items(filter_items: str, response: Response): start = time.time() filter_items = json.loads(filter_items) result = {"message": "Success"} if not filter_items: response.status_code = status.HTTP_400_BAD_REQUEST response.content = {'error': 'empty query params'} return response connect(host=settings.uri) sort_products = list() sort_filter = filter_items.pop('sort') if 'sort' in filter_items else {} paid_companies = Companies.objects(paid=True) if sort_filter.get('paid_companies') else None paid_products = None try: for item in sort_filter.get('products'): sort_products.append(item) except TypeError: pass filter_search = filter_items.copy() query_size = filter_search.pop('query_size') if filter_search.get('query_size') else 30 query_from = filter_search.pop('query_from') if filter_search.get('query_from') else 0 try: filter_search.pop('query_from') except KeyError: pass filter_search['hide'] = True if filter_search.get('hide') else False query_to = query_from + query_size if paid_companies: filter_search['company_collection__in'] = paid_companies paid_products = Products.objects().filter(**filter_search).order_by(*sort_products)[query_from:query_to] query_to = query_to - len(paid_products) filter_search['company_collection__nin'] = paid_companies filter_search.pop('company_collection__in') if paid_products: not_paid_products = Products.objects().filter(**filter_search).order_by(*sort_products)[query_from:query_to] result["items_count"] = paid_products.count() + not_paid_products.count() result["items"] = json.loads(paid_products.to_json()) + json.loads(not_paid_products.to_json()) else: products = Products.objects().filter(**filter_search).order_by(*sort_products)[query_from:query_to] result["items_count"] = products.count() result["items"] = json.loads(products.to_json()) disconnect() stop = time.time() - start result['time_script'] = f"--- {stop} seconds ---" return result
def populate(): """ The method run when environment is set to populate. Iterate through the .csv files and getting every row of every file and populate the database. """ if __name__ == "app.populate_db": try: file_list = [ 'orders', 'order_lines', 'products', 'promotions', 'product_promotions', 'commissions' ] for file_name in file_list: file = open('app/csv_data/' + file_name + '.csv', encoding='utf8') data = reader(file, delimiter=',') next(data) for entry in data: if file_name == 'orders': row = Order(id=entry[0], created_at=datetime.strptime( entry[1], '%d/%m/%Y').date(), vendor_id=entry[2], customer_id=entry[3]) if file_name == 'order_lines': row = OrderLine(order_id=entry[0], product_id=entry[1], product_description=entry[2], product_price=entry[3], product_vat_rate=entry[4], discount_rate=entry[5], quantity=entry[6], full_price_amount=entry[7], discounted_amount=entry[8], vat_amount=entry[8], total_amount=entry[8]) if file_name == 'products': row = Products(id=entry[0], description=entry[1]) if file_name == 'promotions': row = Promotion(id=entry[0], description=entry[1]) if file_name == 'product_promotions': row = ProductPromotion(date=datetime.strptime( entry[0], '%d/%m/%Y').date(), product_id=entry[1], promotion_id=entry[2]) if file_name == 'commissions': row = VendorCommissions(date=datetime.strptime( entry[0], '%d/%m/%Y').date(), vendor_id=entry[1], rate=entry[2]) db.session.add(row) db.session.commit() print('Finished') except Exception as error: print(error)
def add_product(): form = ProductForm() if request.method == 'POST': product = Products(product_name=form.product.data, quantity= form.quantity.data) db.session.add(product) db.session.commit() flash("Your Product has been inserted") return redirect(url_for('products.products')) return render_template('add_product.html', form=form, title='Add Product')
def get(self): """ Get receipt with given ФН, ФД and ФП numbers ФН, ФД and ФП numbers getting from fn, fd and fp query parameters :return: Products from receipt with name, quantity and price of 1 piece of product :rtype: dict/json """ # Parsing request query fields args = receipt_request.parse_args() # Login of authorized user stores in Flask g object user = User.query.filter_by(username=g.user.username).first() # Send request of receipt JSON fts = FtsRequest() request = fts.getReceipt(args['fn'], args['fd'], args['fp'], user.phone, user.fts_key) # Send error JSON if bad request if request['ftsRequestSuccess'] is False: abort(request['responseCode'], message=request['error']) # Extract products info from JSON result = {} result['items'] = [{ 'name': item['name'], 'quantity': item['quantity'] if isinstance(item['quantity'], int) else 1, 'price': item['price'] if isinstance(item['quantity'], int) else item['sum'] } for item in request['items']] try: for item in result['items']: name = item['name'] quantity = item['quantity'] price = int(item['price']) / 100 exists_product = Products.query.filter( Products.product_name == name, cast(Products.price, String()) == str(price), Products.table_id == user.current_table[0].id).first() if exists_product is None: # Create product and add to database new_product = Products( table_id=user.current_table[0].id, product_name=name, count=quantity, price=price) db.session.add(new_product) else: exists_product.count += quantity db.session.commit() # Return JSON return exists_product.table.getProducts() if exists_product is not None else new_product.table.getProducts() except (IntegrityError, IndexError): db.session.rollback() abort(404, message="Username '{}' does not connected to any table".format(user.username))
def ordercsv(): f = request.files['Product'] if not f: return "No file" stream = io.StringIO(f.stream.read().decode("UTF8"), newline=None) csv_input =list( csv.DictReader(stream)) for row in csv_input: us = Products(id=row['id'],SKU=row['SKU'],productName=row['productName'],brand=row['brand'], productDescription=row['productDescription']) db.session.add(us) db.session.commit() return "Data aquired"
def insert_product_list(): # 生成工单-产品演示数据 products = Product.query.all() for o in Order.query.all(): product_list = [] repeat_check = [] for i in range(1, products.__len__()): product = random.randint(1, products.__len__()) if product not in repeat_check: product_list.append(Products(order=o, product_id=product)) repeat_check.append(product) db.session.add_all(product_list) db.session.commit()
def add_product(): ''' add a product to the database ''' add_product = True form = ProductsForm() if form.validate_on_submit(): filename = request.files['image'] _, f_ext = os.path.splitext(filename.filename) name = form.name.data picture_fn = name + f_ext photos.save(filename, name=picture_fn) url = photos.url(picture_fn) product = Products(product_name=form.name.data, product_price=form.price.data, product_image=url, product_description=form.description.data, product_stock=form.stock.data) product.products_categories = form.categories.data try: #add a product to the database db.session.add(product) db.session.commit() gc.collect() flash("You have successfully added a product") except: # in case product name already exists flash("Error: product name already exits") # redirect to the roles page return redirect(url_for('admin.list_products')) #load product template return render_template('admin/products/product.html', add_product=add_product, form=form, title="Add Product")
def addProduct(): from product.forms import AddProductForm form = AddProductForm() if form.validate_on_submit(): product = Products(product_name=form.product_name.data, brand=form.brand.data, categories=form.categories.data, price=form.price.data, image_url=form.image_url.data) db.session.add(product) db.session.commit() db.session.close() flash('You have added a product.') return render_template('search_product.html', form=form) return render_template('add_product.html', form=form)
def test_create_product(): """ GIVEN a new product WHEN when the new product is created THEN the product is added to database """ "" new_product = Products(image='StringType', name='StringType', price=9999999) db.session.add(new_product) db.session.commit() assert new_product.image == 'StringType' assert new_product.name == 'StringType' assert new_product.price == 9999999
def add_products(): p_names = [ "black hoodie logo original", "black hoodie logo secondary", "black hoodie logo small", "black shirt logo original", "black shirt logo secondary", "black shirt logo secondary left", "stickers", "white hoodie logo original", "white hoodie logo secondary", "white shirt logo original", "white shirt logo original left", "white shirt logo secondary left" ], for product in p_names[0]: print(product) if "hoodie" in product: price = 50 elif "shirt" in product: price = 15 else: price = 5 new_product = Products(p_name=product, price=price, accessory=True) db.session.add(new_product) db.session.commit() db.create_all() db.session.commit()
def search(): if not g.search_form.validate(): return render_template('index.html', title='Home') page = request.args.get('page', 1, type=int) products, total = Products.search(g.search_form.q.data, page, current_app.config['PRODUCTS_PER_PAGE']) start = current_app.config['PRODUCTS_PER_PAGE'] * (page-1) if total > current_app.config['PRODUCTS_PER_PAGE'] * page: end = current_app.config['PRODUCTS_PER_PAGE'] * page + 1 else: end = total if start < total: products = products[start:end] next_url = url_for('main.search', q=g.search_form.q.data, page=page + 1) \ if total > page * current_app.config['PRODUCTS_PER_PAGE'] else None prev_url = url_for('main.search', q=g.search_form.q.data, page=page - 1) \ if page > 1 else None return render_template('index.html', title='Search', products=products, total=total, next_url=next_url, prev_url=prev_url, start=start, end=end, query=g.search_form.q.data)
from app.models import User, Products from app import db u1 = User(username='******', email='*****@*****.**') db.session.add(u1) u2 = User(username='******', email='*****@*****.**') db.session.add(u2) u3 = User(username='******', email='*****@*****.**') db.session.add(u3) p = Products( p_name='suits season 1', p_price='5', p_picture='http://ecx.images-amazon.com/images/I/61XzKzRzONL._SL1073_.jpg', users=u1) db.session.add(p) p = Products( p_name='suits season 2', p_price='5', p_picture='http://ecx.images-amazon.com/images/I/91ziEZy5iIL._SL1500_.jpg', users=u1) db.session.add(p) p = Products( p_name='suits season 3', p_price='5', p_picture='http://ecx.images-amazon.com/images/I/81lZwVSwazL._SY550_.jpg', users=u1) db.session.add(p) p = Products(p_name='suits season 4', p_price='5', p_picture='NULL', users=u1) db.session.add(p) p = Products(
def get_products(): page = request.args.get('page', 1, type=int) per_page = min(request.args.get('per_page', 10, type=int), 100) data = Products.to_collection_dict(Products.query, page, per_page, 'api.get_products') return jsonify(data)
def CreateProduct(): body = request.get_json() body['slug'] = slug.slug(body['name']) items = Products(**body).save() return Response(items, mimetype="application/json", status=200)
def admin_panel(): if current_user.email in [ "*****@*****.**", "*****@*****.**", "*****@*****.**", ]: productsform = ProductsFormAdmin() ordersform = OrdersFormAdmin() usersform = UsersFormAdmin() if productsform.submit1.data and productsform.validate(): if productsform.types.data == "list": products = Products.query.all() arr = [] for product in products: arr.append(product) return render_template( "admin_panel.html", title="Admin Panel", products=productsform, products_arr=arr, orders=ordersform, users=usersform, ) if productsform.types.data == "add": try: int(productsform.price.data) except: return render_template( "admin_panel.html", title="Admin Panel", products=productsform, products_arr=[ f"Error! {productsform.price.data} is not an integer!" ], orders=ordersform, ) product = Products( name=productsform.name.data, desc=productsform.desc.data, price=int(productsform.price.data), ) db.session.add(product) db.session.commit() return redirect("/admin_panel") if productsform.types.data == "del": Product = Products.query.filter_by( name=productsform.name.data).first() if Product != None: db.session.delete(Product) db.session.commit() return redirect("/admin_panel") else: return render_template( "admin_panel.html", title="Admin Panel", products=productsform, products_arr=[ f"Error! {productsform.name.data} does not exist" ], orders=ordersform, users=usersform, ) if ordersform.submit2.data and ordersform.validate(): if ordersform.types.data == "list": orders = Orders.query.all() arr = [] for order in orders: arr.append(order) return render_template( "admin_panel.html", title="Admin Panel", products=productsform, orders=ordersform, orders_arr=arr, users=usersform, ) if ordersform.types.data == "del": order = Orders.query.filter_by( order_name=ordersform.order_name.data).first() if order != None: db.session.delete(order) db.session.commit() return redirect("/admin_panel") else: return render_template( "admin_panel.html", title="Admin Panel", products=productsform, orders_arr=[ f"Error! {ordersform.order_name.data} does not exist" ], orders=ordersform, users=usersform, ) if ordersform.types.data == "complete": order = Orders.query.filter_by( order_name=ordersform.order_name.data).first() if order != None: order.order_flag = "completed" db.session.add(order) db.session.commit() else: return render_template( "admin_panel.html", title="Admin Panel", products=productsform, orders_arr=[ f"Error! {ordersform.order_name.data} does not exist" ], orders=ordersform, users=usersform, ) if usersform.submit3.data and usersform.validate(): if usersform.types.data == "search": user = User.query.filter_by( username=usersform.username.data).first() if not user: return render_template( "admin_panel.html", title="Admin Panel", products=productsform, orders=ordersform, users=usersform, userd=["err", "Error! User not found!"], ) user = [user] return render_template( "admin_panel.html", title="Admin Panel", products=productsform, orders=ordersform, users=usersform, userd=user, ) if usersform.types.data == "list": user = User.query.all() return render_template( "admin_panel.html", title="Admin Panel", products=productsform, orders=ordersform, users=usersform, userd=user, ) if usersform.types.data == "delete": user = User.query.filter_by( username=usersform.username.data).first() if not user: return render_template( "admin_panel.html", title="Admin Panel", products=productsform, orders=ordersform, users=usersform, userd=["err", "Error! User not found!"], ) db.session.delete(user) db.session.commit() return render_template( "admin_panel.html", title="Admin Panel", products=productsform, orders=ordersform, users=usersform, userd=["err", "${user} has been removed"], ) return render_template( "admin_panel.html", title="Admin Panel", products=productsform, orders=ordersform, users=usersform, ) else: return render_template("404.html"), 404
def Products(id): items = Products.objects().filter(shop=id).to_json() return jsonify(items), 200
def uploadproducts(request): if request.method == 'POST': form = request.POST # Full path and name to your csv file csv_filepathname=form['mycsvfile']#"D:/likestore/likestore/sample_products.csv" # Full path to your django project directory your_djangoproject_home="D:/likestore/likestore/likestore" import sys,os sys.path.append(your_djangoproject_home) os.environ['DJANGO_SETTINGS_MODULE'] = 'likestore.settings' import csv dataReader = csv.reader(open(csv_filepathname), delimiter=',', quotechar='"') for row in dataReader: if row[0] != 'ProductID': # Ignore the header row, import everything else products = Products() products.productsku = row[0] products.productname = row[1] products.productprice = row[2] products.productweight = row[3] products.productbestfor = row[4] products.productcartdesc = row[5] products.productshortdesc = row[6] products.productlongdesc = row[7] products.productsize = row[8] products.productcolor = row[9] products.productrating = row[10] products.productthumb = row[11] products.productimage = row[12] products.productimage2 = row[13] products.productimage3 = row[14] products.productcategoryid = row[15] products.productupdatedate = row[16] products.productstock = row[17] products.productlive = row[18] products.productunlimited = row[19] products.productlocation = row[20] products.save() products = Products.objects.raw('SELECT * FROM products') template=loader.get_template("admin/tables_datatables.html") rc=RequestContext(request,{'products':products}) return HttpResponse(template.render(rc))
def add_products(): product1 = Products('Cubs-Cap', '2021 season Cubs Baseball Cap', '18', '1', '/static/images/1.jpg') product2 = Products('Glove', 'Wilson A2000 Infield', '20', '1', '/static/images/2.jpg') product3 = Products('BaseBall', 'Rawling MLB Official', '10', '1', '/static/images/3.jpg') product4 = Products('MBL T-Shirt', 'MLB Official 2021 ', '9', '1', '/static/images/4.jpg') product5 = Products('Bat', 'Rawling R45 short_Swing Bat', '15', '1', '/static/images/5.jpg') product6 = Products('Batting Helmet', 'Molded Batting Helmet', '11', '1', '/static/images/6.jpg') product7 = Products('Cleat', 'Nike,Soccer Cleat', '250', '2', '/static/images/7.jpg') product8 = Products('Gear Bag', 'Nike Official Gear-Bag', '70', '2', '/static/images/8.jpg') product9 = Products('Goalkeeper Glove', 'Adidas Golkeeper Glove', '70', '2', '/static/images/9.jpg') product10 = Products('Soccer Socks', 'Under Armour Over The Calf Socks', '15', '2', '/static/images/10.jpg') product11 = Products('Shinguards', 'Adults X League Shinguards', '20', '2', '/static/images/11.jpg') product12 = Products('Jersey', 'Leo Messi La-Liga Season 2020 Jersey', '50', '2', '/static/images/12.jpg') product13 = Products('Basketball', 'Neverflat Comp Basketball 29.5', '40', '3', '/static/images/13.jpg') product14 = Products('Net', 'All-Weather R/W/B Net', '5', '3', '/static/images/14.jpg') product15 = Products('Back Atcha', 'Spalding Ball Return Training Aid', '15', '3', '/static/images/15.jpg') product16 = Products('Basketball Shoe', 'Under Armor Unisex Basketball Shoe', '10', '3', '/static/images/16.jpg') product17 = Products('Nike-A', 'Nike Elite Basketball Crew Socks X-Large', '15', '3', '/static/images/17.jpg') product18 = Products('Mcdavid', '6500 Compression Arm Sleeve ', '8', '3', '/static/images/18.jpg') db.session.add(product1) db.session.add(product2) db.session.add(product3) db.session.add(product4) db.session.add(product5) db.session.add(product6) db.session.add(product7) db.session.add(product8) db.session.add(product9) db.session.add(product10) db.session.add(product11) db.session.add(product12) db.session.add(product13) db.session.add(product14) db.session.add(product15) db.session.add(product16) db.session.add(product17) db.session.add(product18) db.session.commit()
def import_excel(request): template_url = 'products/import-excel.html' operator = Operators.login_required(request) if operator is None: Operators.set_redirect_field_name(request, request.path) return redirect(reverse("operators_signin")) else: auth_permissions = Operators.get_auth_permissions(operator) if settings.ACCESS_PERMISSION_OPERATOR_UPDATE in auth_permissions.values( ): if operator.operator_type != Operators.TYPE_SUPER_ADMIN: return HttpResponseForbidden('Forbidden', content_type='text/plain') else: if request.method == 'POST': form = ProductExcelImportForm(request.POST, request.FILES) if form.is_valid(): if 'excel_file' in request.FILES and \ request.FILES['excel_file']: excel_file = form.cleaned_data['excel_file'] import pandas as pd df = pd.read_excel(excel_file) matrix = df.values df = pd.DataFrame(df) error = '' success = 0 failed = 0 for index, row in df.iterrows(): print(index, row) try: type = row['type'] tag = row['tag'] title = row['title'] category = row['category'] fail = False try: product = Products.objects.get( product_tag=tag) except Products.DoesNotExist: product = None if product is None: product = Products() product.product_code = Products.generate_random_number( 'product_code', 8) product.product_sub_title = '' product.product_quantity_available = 0 product.product_quantity_unit = '' product.product_type = type product.product_tag = tag product.product_category = category product.product_title = title product.product_updated_at = Utils.get_current_datetime_utc( ) product.product_updated_id = operator.operator_id product.product_updated_by = operator.operator_name product.product_updated_department = operator.operator_department product.product_updated_role = operator.operator_role product.save() success = success + 1 except Exception as e: failed = failed + 1 error = error + " <br> " + 'Error - [Row: ' + str( index) + '] ' + str(e) message = 'Success: ' + str( success) + ', Failed: ' + str(failed) message = message + error messages.warning(request, message) form = ProductExcelImportForm() return render( request, template_url, { 'section': settings.BACKEND_SECTION_SETTINGS, 'title': Products.TITLE, 'name': Products.NAME, 'operator': operator, 'auth_permissions': auth_permissions, 'form': form, }) else: messages.error( request, 'Error: Select excel file to import.') return render( request, template_url, { 'section': settings.BACKEND_SECTION_SETTINGS, 'title': Products.TITLE, 'name': Products.NAME, 'operator': operator, 'auth_permissions': auth_permissions, 'form': form, }) else: messages.error(request, 'Error: invalid form inputs.') return render( request, template_url, { 'section': settings.BACKEND_SECTION_SETTINGS, 'title': Products.TITLE, 'name': Products.NAME, 'operator': operator, 'auth_permissions': auth_permissions, 'form': form, }) else: form = ProductExcelImportForm() return render( request, template_url, { 'section': settings.BACKEND_SECTION_SETTINGS, 'title': Products.TITLE, 'name': Products.NAME, 'operator': operator, 'auth_permissions': auth_permissions, 'form': form, }) else: return HttpResponseForbidden('Forbidden', content_type='text/plain')
def itemDetailView(request, id): print(request, id) product = Products.get_product_by_id(id) print(product) return render(request, "itemDetail.html", {"product": product})
for index, row in data.iterrows(): result = re.search( r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))", row["image"]) image = result.group(1) name = row["product_name"] all_products.append({"name": name, "image": image}) print("All product details extracted from CSV file") with app.app_context(): # Inital setup. Create DB and Add all products. db.create_all() for prod in all_products: p = Products(name=prod['name'], image_url=prod['image'], public_key=uuid.uuid4().hex) db.session.add(p) db.session.commit() print("All products are added.") # Creating all sample reviews. prods = Products.query.all() for p in prods: for i in range(random.randint(1, 9)): rat_rev = random.choice(sample_reviews) review = Reviews(product=p, review_string=rat_rev[0], rating=rat_rev[1], status="PROCESSED") db.session.add(review)
def __getProductsInPage(self, app, db): resultData = self.page.find('div', {'id': 'resultsCol'}) if resultData is None or resultData == []: return None with app.app_context(): products = [] for result in resultData.find_all('div', {'class': 's-item-container'}): # Skip if empty if result.text is None or result.text == "": continue # Count for product found self.counter['found'] += 1 # Get the product features featuresTag = result.find('div', {'class': 'extension-features'}) # Skip if it isn't a merch product if featuresTag is None or featuresTag.get('ismerch') != 'true': continue # Count for merch product self.counter['merch'] += 1 # Get product rank display_rank = result.find('span', {'class': 'extension-rank'}) if display_rank: rank = int(display_rank.text[1:].replace(',','')) display_rank = display_rank.text else: # Rank Not found, use the default extremely large value rank = DEFAULT_RANK_NOT_FOUND display_rank = 'Rank Not Found' # Get asin from asin tag asinTag = result.find('span', {'class': 'xtaqv-copy'}) asin = asinTag.text # Check if the product exists in database, then update the rankself. # Otherwise, add new product info product = Products.query.filter_by(asin=asin).first() if product: product.rank = rank product.display_rank = display_rank else: # Count for new merch product found self.counter['new'] += 1 # Get features and remove redundant spaces features = re_sub(r'\s{2,40}', ' ', featuresTag.text).lower() # Get name, image link from img tag imgTag = result.find('img', {'class': 's-access-image cfMarker'}) name = imgTag.get('alt') image = imgTag.get('src') # Create a new product product = Products(name=name, asin=asin, image=image, rank=rank, display_rank=display_rank, features=features) # Add to the database session db.session.add(product) db.session.commit()
def get_products(): """ Returns a list of all the products """ return jsonify(Products.get_all_products()), 200