def new_product(self, bot, update): """ Inserts a product into the database linked to chat """ text = update.message.text commands = text.split(" ") commands[-1] = commands[-1].replace(",", ".") if (isinteger(commands[-1]) and commands[-1].find(".") == -1): commands[-1] += ".00" if (len(commands) >= 3 and isfloat(commands[-1])): name = " ".join(commands[1:-1]) price = commands[-1] product = Product(chat=update.message.chat.id, name=name, price=price, quantity=0) db.SESSION.add(product) db.SESSION.commit() update.message.reply_text("Procuct succesfully added") else: update.message.reply_markdown( "To add a new product, type:\n*/newProd* <name of product> <price>" )
def add(): try: product_line = request.form['product_line'] product_name = request.form['product_name'] part_no = request.form['part_no'] label = request.files['label'] csd = request.files['csd'] label.save( "/home/mohamed/Desktop/Management_app/Management-app/label/" + label.filename) csd.save("/home/mohamed/Desktop/Management_app/Management-app/csd/" + csd.filename) try: product = Product(product_line=product_line, product_name=product_name, part_no=part_no, csd=csd.filename, label=label.filename) session.add(product) session.commit() return jsonify({"msg": "success"}) except Exception as e: print(e) session.rollback() return jsonify({"msg": "failed"}) except Exception as e: print(e)
def create_product(name, description, condition, price, image, categories, seller_id): image_url = None if image is not None: try: image_url = _upload_image(image) except Exception as e: return e new_product = Product(name=name, description=description, condition=condition, price=price, sold=False, image=image_url, seller_id=seller_id) new_product.categories = [] categories = [c.strip() for c in categories.split(',')] for category in categories: category = _get_or_create_category(category) new_product.categories.append(category) db.session.add(new_product) db.session.commit() serialized_product = new_product.serialize() serialized_product['categories'] = [ c.serialize() for c in new_product.categories ] return serialized_product
def newProduct(): if 'username' not in login_session: return redirect('/login') templateData = {'name': '', 'description': '', 'price': '', 'type': '', } if request.method == 'POST': if (request.form.get('name') is None or request.form['name'] == "" or request.form.get("description") is None or request.form['description'] == "" or request.form.get('price') is None or request.form['price'] == ""): templateData = {'name': request.form.get('name'), 'description': request .form.get('description'), 'price': request.form.get('price'), 'type': int(request.form.get('type')) } product_types = (session.query(ProductType) .order_by(asc(ProductType.type))) return render_template('newProduct.html', product_types=product_types, templateData=templateData) else: image = request.files['image'] if image.filename is not None: if image and allowed_file(image.filename): filename = secure_filename(image.filename) image.save(os.path.join(app. config['UPLOAD_FOLD'], filename)) product = Product(name=request.form['name'], slug=slugify(request.form['name']), description=request .form.get('description'), price=request.form.get('price'), user_id=login_session['user_id'], product_type_id=int(request.form .get('type')), image_path='img/' + image.filename if image.filename else '') session.add(product) session.commit() flash('New Product added Successfully Created') return redirect(url_for('products')) else: product_types = (session.query(ProductType) .order_by(asc(ProductType.type))) return render_template('newproduct.html', product_types=product_types, templateData=templateData)
def process_item(self, item, spider): """ for x in item['images']: print x['path'] print '-' * 60 """ try: county = session.query(Area).filter( Area.name.like('%s%%' % item['county'])).first() city = session.query(Area).filter(Area.id == county.pid).first() province = session.query(Area).filter_by(id=city.pid).first() province.id except: log.msg(u'未找到省市区县 %s' % item['url'], level=log.WARNING) return item p = Product() p.title = item['title'] p.body = item['body'] p.created = item['created'] p.phone = item['phone'] p.contact = item['contact'] p.address = item['address'] p.city = county.pid p.province = province.id p.county = county.id p.category = item['category'] p.price = item['price'] session.add(p) try: session.commit() except: session.rollback() log.msg(item, level=log.ERROR) return item for img in item['images']: imgp = Myfile() imgp.path = img['path'] #print img['path'] imgp.product_id = p.id session.add(imgp) try: session.commit() except: log.msg(u'图片保存不成功 %s' % item['url'], level=log.WARNING) session.rollback() return item
async def post(self): try: product = await self.request.json() product = Product(**product) await product.commit() return web.json_response({"data": product.dump()}, status=status.HTTP_201_CREATED) except json.decoder.JSONDecodeError: return web.json_response( {"message": "Syntax error in the request body."}, status=status.HTTP_400_BAD_REQUEST) except marshmallow.exceptions.ValidationError as e: return web.json_response({"message": e.messages}, status=status.HTTP_400_BAD_REQUEST) except: return web.json_response({"message": "Unknown error."}, status=status.HTTP_400_BAD_REQUEST)
def post(self): args = parser.parse_args() if not args.get("name"): abort(400, message="name is required") if (args.get("price") or 0) <= 0: abort(400, message="price needs to be higher than 0") p = Product(name=args["name"], price=args["price"]) img = args.get("image") if img: if "." in img.filename: ext = args["image"].filename.split(".")[1] else: ext = "jpg" fname = f"{uuid.uuid4()}.{ext}" img.save(os.path.join("media", fname)) p.image = fname p.save() return _to_json(p), 201
def add_item(): if item_category not in buttons.category_simple_list: item_category_buttons = input('Как назовем список с названием категории?(внутренне название) Напишите название: ') print ('OK! Тебе нужно будет самому создать в файле buttons.py list с этим именем, все оствльное создам автоматом!') buttons.category_simple_list.extend(item_category) buttons.category[item_category] = item_category_buttons try: buttons.item_category_buttons.append(InlineKeyboardButton(item_name, callback_data = item_name) except: print('ну я же говорил, создай List!') with open('auchan_replace.csv', 'a', encoding='utf-8') as f: fields =['name_old', 'name_new'] writer = csv.DictWriter(f, fields, delimiter =';') for row in writer: writer.writerow(item_name_auchan,item_name) with open('metro_replace.csv', 'a', encoding='utf-8') as f: fields =['name_old', 'name_new'] writer = csv.DictWriter(f, fields, delimiter =';') for row in writer: writer.writerow(item_name_metro,item_name) with open('perekrestok_replace.csv', 'a', encoding='utf-8') as f: fields =['name_old', 'name_new'] writer = csv.DictWriter(f, fields, delimiter =';') for row in writer: writer.writerow(item_name_perekrestok,item_name) auchan_parcer.url_list.append(item_url_auchan) metro_parser.url_list.append(item_url_metro) perekrestok_parser.url_list.append(item_url_perekrestok) prod = Product(name = item_name) db_session.add(prod) db_session.commit() print ('OK! ') if item_name not in buttons.item_list: buttons.item_list.extend(item_name) add_item() else: print('Товар уже существует')
from sqlalchemy.orm import sessionmaker from db import Product, engine Session = sessionmaker(bind=engine) session = Session() p = Product(code='IPX', name='IPhone X', price=10500000) session.add(p) session.commit() p = session.query(Product).filter(Product.code == 'IPX').first() print(p.name)
def fab_config(self, bot, update): """ Adds all products used in FSW """ product = Product(chat=update.message.chat.id, name="Guaraná", price="1.50", quantity=0) db.SESSION.add(product) product = Product(chat=update.message.chat.id, name="Coca-Cola", price="1.50", quantity=0) db.SESSION.add(product) product = Product(chat=update.message.chat.id, name="Fanta", price="2.50", quantity=0) db.SESSION.add(product) product = Product(chat=update.message.chat.id, name="Schweppes", price="2.50", quantity=0) db.SESSION.add(product) product = Product(chat=update.message.chat.id, name="Sprite", price="2.50", quantity=0) db.SESSION.add(product) product = Product(chat=update.message.chat.id, name="Suco Maçã", price="2.00", quantity=0) db.SESSION.add(product) product = Product(chat=update.message.chat.id, name="Suco Goiaba", price="2.00", quantity=0) db.SESSION.add(product) product = Product(chat=update.message.chat.id, name="Suco Caju", price="2.00", quantity=0) db.SESSION.add(product) product = Product(chat=update.message.chat.id, name="Suco Uva", price="2.00", quantity=0) db.SESSION.add(product) product = Product(chat=update.message.chat.id, name="Paçoquinha", price="0.50", quantity=0) db.SESSION.add(product) product = Product(chat=update.message.chat.id, name="Pé de Moça", price="1.00", quantity=0) db.SESSION.add(product) product = Product(chat=update.message.chat.id, name="Oreo", price="2.50", quantity=0) db.SESSION.add(product) product = Product(chat=update.message.chat.id, name="Teens Chocolate", price="1.50", quantity=0) db.SESSION.add(product) product = Product(chat=update.message.chat.id, name="Bolinho Cenoura", price="1.00", quantity=0) db.SESSION.add(product) product = Product(chat=update.message.chat.id, name="Bolinho Brigadeiro", price="1.00", quantity=0) db.SESSION.add(product) db.SESSION.commit() update.message.reply_text("Products successfully added")
from telebot import * from db import Product TOKEN = "1883154030:AAGF21aoXyK3TYzLvlrRrOqxKUG6rObEG2U" bot = TeleBot(TOKEN) products = Product("product.sql") # products.create_table() name = "" amount = "" price = "" category = "" @bot.message_handler(commands=['start']) def greeting(message): bot.send_message(message.chat.id, "Напиште что хотите сделать") @bot.message_handler(commands=['create']) def create_product(message): bot.send_message(message.chat.id, "Введите название товара:") bot.register_next_step_handler(message, ask_amount) @bot.message_handler(commands=['show']) def show_products(message): data = products.select_products() for product in data: temp = "ID: " + product[0] + "\n" + "Name: " + product[1] + "\n" + "Amount: " + str(product[2]) + "\n" + "Price: " + str(product[3]) + "\n" + "Category: " + product[4] bot.send_message(message.chat.id, temp)
from db import db_session, Product import buttons for item in buttons.item_list: prod = Product(name=item) db_session.add(prod) db_session.commit()
#wait_event = WebDriverWait(driver, 10) spec_values = wait_event.until(EC.presence_of_all_elements_located((By.XPATH, '//div[@class="specListItem col-sm-9 col-xs-8 pad10 "]'))) spec_values = [v.text for v in spec_values] for stog_cnt in range(len(storages)): for spc_cnt in range(len(specs_names)): item = Product( store = 'verizon', product_name = product_name, skuId = skuId, brand = brand, color = colors, storage = storages[stog_cnt], price = prices[stog_cnt], spec_name = specs_names[spc_cnt], spec_value = spec_values[spc_cnt], ) item.save() # Click review button to go to the review section review_button = driver.find_element_by_id('reviewsLink') review_button.click() #overall review if num_reviews >0: overall_elm = overall_elm = driver.find_element_by_xpath('.//div[@class=" row noSideMargin deviceReviews border_bottomBlack padTop10 padBottom24"]') overall_text = re.findall(r'[\d.]+', overall_elm.find_element_by_xpath('.//div[@class="col-xs-6 noSidePad pad5"]').text)