def setup(self): self.service = Repair('Аренда', 2, 100) self.coffee_machines = [ CoffeeMachine('Lirica', 20, Brand('Saeco')), CoffeeMachine('Jura', 5, Brand('X9')) ] self.catlog = Repair('Repair', 300, 2, self.coffee_machines)
def handle_brands(): if request.method == 'GET': return jsonify(Brand.getAllSerialized()), 200 if request.method == 'POST': body = request.get_json() newBrand = Brand.newInstance(body) newBrand.addCommit() return toJson(newBrand), 201
def post(self): parsed_args = parser.parse_args() brand = Brand() brand.name = parsed_args['name'] brand.website = parsed_args['website'] session.add(brand) session.commit() return brand, 201
def mutate(root, info, brand): if not brand.brand_id: brand.brand_id = len(BrandModel.objects) + 1 brand_obj = BrandModel( name = brand.name, country = brand.country, brand_id = brand.brand_id ) brand_obj.save() return createBrand(brand=brand_obj)
def create_brand(): auth_token = request.args.get('access_token') try: keys = bu.decode_auth_token(auth_token) except jwt.ExpiredSignatureError: return jsonify({'message': 'Signature expired. Please log in again.'}), 401 except jwt.InvalidTokenError: return jsonify({'message': 'Invalid token. Please log in again.'}), 401 admin = keys[0] id = keys[1] if admin == 0: return jsonify({'response': "This is not an admin"}), 403 data = request.get_json() if not data: return {"response": "No input data provided"}, 400 try: result = BrandSchema().load(data) except Exception: return jsonify({'response': "Invalid input"}), 403 brand = Brand(name=result["name"]) db.session.add(brand) db.session.commit() return jsonify({'response': "Success"}), 201
def setup(self): self.brand = Brand('Saeco') item_factory = ItemFactory() self.coffee = item_factory.create_item('coffee', 'Gold', 12, brands=[self.brand]) self.coffee_machine1 = CoffeeMachine('Lirica', 20, self.brand) self.coffee_machine2 = CoffeeMachine('One Touch', 20, self.brand) self.repair = item_factory.create_item( 'repair', name='Program', quantity=30, coffee_machines=[self.coffee_machine1, self.coffee_machine2], price=100) self.coffee_machine3 = CoffeeMachine('Any', 20, self.brand) self.compilation = item_factory.create_item('compilation', name='by me', quantity=30, theme='Program') files = [self.repair, self.coffee, self.coffee_machine3] for f in files: self.compilation.items.append(f)
def api_brand_insert(): new_brand = request.get_json() brand = Brand(id=new_brand['id'], name=new_brand['name']) db.session.add(brand) db.session.commit() brand_json = {"id": brand.id, "name": brand.name} return jsonify(brand_json)
def test_create_item(): brand = Brand('Sirocco') item_factory = ItemFactory() coffee_item = item_factory.create_item('coffee', name='Espresso', quantity=20, brands=[brand]) assert isinstance(coffee_item, OrderItem) assert isinstance(coffee_item, Coffee) assert coffee_item.name == 'Espresso' assert brand in coffee_item.brands with raises(Exception): item_factory.create_item('coffee', name='Espresso', quantity=20, brand=brand) with raises(TypeError): item_factory.create_item('coffee', name='Espresso', quantity=20, brand=brand) coffee_machine_item = item_factory.create_item('coffee_machine', name='Jura', quantity=10, brand=Brand('Saeco')) assert isinstance(coffee_machine_item, OrderItem) assert isinstance(coffee_machine_item, CoffeeMachine) repair_item = item_factory.create_item( 'repair', name='Ремонт чего-то', quantity=30, coffee_machines=[coffee_machine_item], price=100) assert isinstance(repair_item, OrderItem) assert isinstance(repair_item, Repair) with raises(KeyError): item_factory.create_item('what', name='what', quantity=1) compilation_item = item_factory.create_item('compilation', name='by me', quantity=30, theme='Program') assert isinstance(compilation_item, OrderItem) assert isinstance(compilation_item, Compilation)
def delete_brand(title): brand = Brand.objects(title=title) if brand: brand.delete() else: return False return True
def get_or_create_brand(session, brand_name, label): brand = session.query(Brand).filter(Brand.name == brand_name).first() print(brand) if not brand: brand = Brand(name=brand_name, label=label) session.add(brand) return brand
def parse_actions(): logging.info('Парсинг акций всех брендов') brands = Brand.select() for brand in brands: try: parse_actions_of_brand(brand.id, brand.link) i += 1 except Exception as ex: logging.error(str(ex))
def parse_brands(): """ Получение и запись списка брендов в таблицу brands """ logging.info("Парсинг брендов") soup = get_soup_page_by_link('https://proactions.ru/brands/') lists = soup.find(id='content').findAll('li') count = 0 for e in lists: try: articles = e.a.attrs if articles['href']: Brand.create(name=e.text, link='https://proactions.ru' + e.a.attrs['href']) count += 1 except Exception as ex: logging.error(str(ex)) logging.info(f'Записано {count} брендов')
def test_init(self): assert self.coffee.name == 'Mocca' assert self.coffee.quantity == 5 assert len(self.coffee.brands) == 2 self.coffee.brands.append(Brand('Kate')) assert len(self.coffee.brands) == 3 assert self.sirocco in self.coffee.brands assert self.lasemeuse in self.coffee.brands assert self.coffee.brands is self.brands
def save(self): """Save data in target table.""" if self.table == "Category": Category(self.db).insert_query(self.elements) elif self.table == "Brand": Brand(self.db).insert_query(self.elements) elif self.table == "Store": Store(self.db).insert_query(self.elements) elif self.table == "Product": Product(self.db).insert_query(self.elements)
def shipping(): tags = [product.name for product in Product.select()] tags += [descriptor.description for descriptor in Descriptor.select()] tags += [brand.name for brand in Brand.select()] tags.sort() return render_template( "shipper_dashboard.html", Order=Order, Stock=Stock, tags=tags, fn=fn, current_user=current_user )
def addbrand(): if request.method == 'POST': form = BrandForm(request.form) if form.validate(): brand = Brand(name=form.name.data) db.session.add(brand) db.session.commit() flash('Brand "%s" created successfully.' % brand.name, 'success') return redirect(url_for('products.index', slug=brand.slug)) else: form = BrandForm() return render_template('products/addbrand.html', form=form)
def buyer(): stocks = Stock.select().where(Stock.bought == False) stocks = [ {"id": json.dumps(str(stock.id)), "stock": stock} for stock in stocks ] # this will be used for adding listings to the homepage tags = [product.name for product in Product.select()] tags += [descriptor.description for descriptor in Descriptor.select()] tags += [brand.name for brand in Brand.select()] tags.sort() return render_template("buyer_dashboard.html", stocks=stocks, Order=Order, Stock=Stock, tags=tags, fn=fn)
def __init__(self, db_connection): """Please see help(Navigation) for more details.""" self.view = Display() self.db = db_connection self.category_table = Category(db_connection) self.product_table = Product(db_connection) self.brand_table = Brand(db_connection) self.substitution_table = Substitution(db_connection) self.current_pos = 0 self.selections = { "category": None, "sub_category": None, "name": None, "brand": None, "brand_name": None, "nutri_score": None, "substitute": None, "substitute_brand": None } self.active = self.main
def get_all_brands(db='catalogIndex', page=1, limit=100): if db.lower() == "catalogindex": brands = [brand.to_json() for brand in Brand.objects()[(page-1)*limit: page*limit]], Brand.objects().count() elif db.lower() == "power": brands = [{ 'title': brand.title, 'title_edit': brand.title_edit, 'title_cn': brand.title_cn, 'global_searchs': brand.global_searchs, } for brand in PowerBrand.objects()], PowerBrand.objects().count() return brands
def init_db(): brand = Brand(name='Ford', brand_id=1, country='US').save() Brand(name='Ford2', brand_id=2, country='US').save() brand.save() fiesta = Car(brand=brand, name='Fiesta', car_id=1) edge = Car(brand=brand, name='Edge', car_id=2) ecosport = Car(brand=brand, name='Ecosport', car_id=3) ka = Car(brand=brand, name='Ka', car_id=4) flex_counter = 0 gas_counter = 0 for car in [fiesta, edge, ecosport, ka]: flex_counter += 1 gas_counter += 1 car.save() flex_version = Version(price=random.randrange(0, 50000), model=car, name='{name} {fuel} - {year}'.format( name=car.name, fuel='Flex', year=2011, version_id=flex_counter)) gasoline_version = Version(price=random.randrange(0, 50000), model=car, name='{name} {fuel} - {year}'.format( name=car.name, fuel='Gasolina', year=2011, version_id=gas_counter)) flex_version.save() gasoline_version.save()
def test_create_db_and_record(): create_db_tables() gibson = Brand.create(name='Gibson') usa = SubBrand.create(name='USA', brand=gibson) les_paul = Range.create(name='Les Paul', brand=gibson) standard = Model.create(name='Standard', brand=gibson) guitar = Guitar.create(variant=None, year=2018, price=3399, brand=gibson, sub_brand=usa, range_name=les_paul, model=standard)
def get_searchs(): brands = [] for b in Brand.objects(is_delete=False): if b.title_edit != "": brand = b.title_edit else: brand = b.title brands.append(brand) ks = KeywordSearch() for i in range(len(brands)/50): thebrands = brands[i*50:i*50+50] kwdict = ks.search(thebrands) for kw, result in kwdict.iteritems(): gs, ls = result gs, ls = int(gs), int(ls) print kw, gs, ls
def check_brand(brand_name): """ Checks if brand is available in database already, else adds and returns id :param brand_name: Name of the brand to search in database. :return: int: Id of the brand that already exists/is inserted in the database. """ brand = Brand.query.filter_by(brand_name=brand_name).first() if brand is None: # Brand doesn't exist in database, so insert it and return brand_id new_brand = Brand(brand_name=brand_name) db.session.add(new_brand) db.session.flush() brand_id = Brand.query.filter_by( brand_name=brand_name).first().brand_id else: # Brand already exists in database, so return brand_id brand_id = brand.brand_id return brand_id
def import_data(): session = Session() client = OpenFoodFactsApi() categories = client.get_categories() stores = client.get_stores() # product_schema = ProductSchema() # insert data to Category for store in stores: store1 = Store(name=store) session.add(store1) for cat in categories: category1 = Category(name=cat) print(category1) products = client.get_products(cat) # insert data to Product, Store, Brand for product in products: if product.get("product_name") != "": b = session.query(Brand).filter( Brand.name == product.get("brands")).first() if not b: brand = Brand(name=product.get("brands"), label=product.get("label")) session.add(brand) b = session.query(Brand).filter( Brand.name == product.get("brands")).first() product = Product( name=product.get("product_name"), nutriscore=product.get("nutrition_grades"), nova=product.get("nova_groups_tags"), brand=b, url=product.get("url"), barcode=product.get("code")) product.categories.append(category1) product.stores.append(store1) print(product) session.add(product) session.commit() # dump_data = product_schema.dump(product) # load_data = product_schema.load(dump_data, session=session) session.close()
def setup(self): self.brand = Brand('Saeco') self.coffee_machine = CoffeeMachine('Lirica', 20, self.brand)
class Navigation(): """This class represents the app navigation tree. Arguments: db_connetcion {<class records.Database>} -- database connection Attributes: db {<class records.Database>} -- database connection view {<class views.Display>} -- manage the user interface category_table {<class models.Category>} -- manage queries on category table brand_table {<class models.Brand>} -- manage queries on brand table product_table {<class models.Product>} -- manage queries on product table substitution_table {<class models.Substitution>} -- manage queries on substitution table current_pos {int} -- track where the user is in the navigation tree selections {dict} -- keep all the choices of the user active {func} -- active method """ def __init__(self, db_connection): """Please see help(Navigation) for more details.""" self.view = Display() self.db = db_connection self.category_table = Category(db_connection) self.product_table = Product(db_connection) self.brand_table = Brand(db_connection) self.substitution_table = Substitution(db_connection) self.current_pos = 0 self.selections = { "category": None, "sub_category": None, "name": None, "brand": None, "brand_name": None, "nutri_score": None, "substitute": None, "substitute_brand": None } self.active = self.main def main(self): """Control the main menu. Returns: func|False -- Call another method or return False to quit. """ self.current_pos = 0 self.view.template_menu(self.current_pos) choice = self.view.make_choice() if choice == 3: print("A bientôt") return False elif choice == 2: self.active = self.all_substitutions elif choice == 1: self.categories_options = \ self.category_table.select_five_main_categories() self.active = self.categories else: print("veuillez entrer un nombre valide") return self.active() def categories(self): """Control the categories menu. Returns: func -- Call another method """ self.current_pos = 1 self.view.template_menu(self.current_pos, self.categories_options) choice = self.view.make_choice() if choice == 0: self.active = self.main return self.active() try: category_selected = self.categories_options[choice - 1] except IndexError: print("Aucun choix ne correspond à ce numéro," "veuillez sélectionner un numéro valide") else: category_id = self.category_table.select_id_by_name( category_selected) self.selections["category"] = category_id self.sub_categories_options = \ self.category_table.select_sub_categories( self.selections) self.active = self.sub_categories return self.active() def sub_categories(self): """Control the subcategories menu. Returns: func -- Call another method """ self.current_pos = 2 self.view.template_menu(self.current_pos, self.sub_categories_options) choice = self.view.make_choice() if choice == 0: self.active = self.categories return self.active() try: category_selected = self.sub_categories_options[choice - 1] except IndexError: print("Aucun choix ne correspond à ce numéro," "veuillez sélectionner un numéro valide") else: sub_category_id = self.category_table.select_id_by_name( category_selected) self.selections["sub_category"] = sub_category_id self.products_options = \ self.product_table.select_product_list_by_category( self.selections) self.active = self.products return self.active() def products(self): """Control the products menu. Returns: func -- Call another method """ self.current_pos = 3 self.view.template_menu(self.current_pos, self.products_options) choice = self.view.make_choice() if choice == 0: self.active = self.sub_categories return self.active() try: product_selected = self.products_options[choice - 1] except IndexError: print("Aucun choix ne correspond à ce numéro," "veuillez sélectionner un numéro valide") else: self.selections["name"] = product_selected[0] self.selections["brand_name"] = product_selected[1] self.selections["brand"] = self.brand_table.select_id_by_name( product_selected[1]) self.selections["nutri_score"] = \ self.product_table.get_nutri_score_by_name( self.selections) if self.selections["nutri_score"] == 'a': print("Cet aliment est déjà sain, c'est super ! Bon appétit") else: better_products = self.product_table.get_better_products( self.selections) if len(better_products) == 0: print("Aucun aliment n'est plus sain " "dans la même catégorie !") else: self.substitute = random.choice(better_products) self.selections["substitute"] = self.substitute.name self.selections["substitute_brand"] = self.substitute.brand self.active = self.substitute_proposition return self.active() def substitute_proposition(self): """Control the substitute proposition menu. Returns: func -- Call another method """ self.current_pos = 4 self.view.substitute_proposition(self.selections, self.substitute) choice = self.view.make_choice() if choice == 1: try: self.substitution_table.insert_query(self.selections) except Exception as e: print("Erreur dans l'enregistrement") # print(e) else: print("Enregitrement effectué avec succès !") elif choice != 2: print("Aucun choix ne correspond à ce numéro," "veuillez sélectionner un numéro valide") self.selections = {k: None for k in self.selections.keys()} self.active = self.main return self.active() def all_substitutions(self): """Get and display all substitutions saved.""" self.current_pos = 5 results = self.substitution_table.get_all() self.view.substitutes(results) self.active = self.main return self.active()
def add_csv_to_db(filename): with open(filename) as csv_file: csv_rows = csv.reader(csv_file, delimiter=';') i = 0 types_ok = True for row in csv_rows: ( arg_brand, arg_sub_brand, arg_range_name, arg_model, arg_variant, arg_year, arg_price ) = row try: arg_year = int(arg_year) arg_price = float(arg_price) except ValueError: types_ok = False print("!! type not ok") if types_ok: brand, new_brand = Brand.get_or_create( name=arg_brand ) sub_brand, new_sub_brand = SubBrand.get_or_create( name=arg_sub_brand, brand=brand ) range_name, new_range = Range.get_or_create( name=arg_range_name, brand=brand ) model, new_model = Model.get_or_create( name=arg_model, brand=brand ) guitar, new_guitar = Guitar.get_or_create( variant=arg_variant, year=arg_year, price=arg_price, brand=brand, sub_brand=sub_brand, range_name=range_name, model=model ) if new_brand: print(f"Brand added: {brand.name}") if new_sub_brand: print(f"Sub-brand added: {sub_brand.name}") if new_range: print(f"Range added: {range_name.name}") if new_model: print(f"Model added: {model.name}") if new_guitar: print(f"Guitar added: {brand.name} {sub_brand.name} " f"{range_name.name} {model.name} {arg_variant} " f"{arg_year} ${arg_price:.2f}")
def setup(self): self.sirocco = Brand('Sirocco') self.lasemeuse = Brand('La Semeuse') self.brands = [self.sirocco, self.lasemeuse] self.coffee = Coffee(name='Mocca', brands=self.brands, quantity=5)
def test_eq(self): assert self.sirocco != self.lasemeuse assert self.sirocco == self.sirocco # Авторы равны когда равны их имена assert self.sirocco == Brand('Sirocco')
def setup(self): self.sirocco = Brand('Sirocco') self.lasemeuse = Brand('La Semeuse')
def search_brands(q): brands = Brand.objects( Q(title__icontains=q)|Q(title_edit__icontains=q)|Q(title_cn__icontains=q) ) return [brand.to_json() for brand in brands]