def bootstrap(request): for i in range(0, 15): user = User.objects.create_user(username='******' + str(i), password='******' + str(i), first_name='Loja Teste ' + str(i)) confs = Configuration(plano='PREMIUM', tema='skin-black') confs.save() bairro = Bairro.objects.get(nome='Centenario') loja = Estabelecimento(user=user, configuration=confs, is_approved=True, photo='http://placehold.it/100x100', cnpj='40.213.932/0001-37', phone='83 30345599', endereco='Rua Manoel da Costa Sales', numero='123', complemento=' ', bairro=bairro) loja.save() for j in range(0, 8): cat = Categoria(estabelecimento=loja, nome='Categoria ' + str(j)) cat.save() for k in range(0, 5): prod = Produto(nome='Produto ' + str(k), descricao='O melhor produto da cidade', preco_base='12', categoria=cat, disponivel=True) prod.save() for w in range(0, 3): grup = Grupo(produto=prod, identificador='id_' + str(w), titulo='Grupo ' + str(w), limitador='2', obrigatoriedade=True, disponivel=True) grup.save() for t in range(0, 5): opc = Opcional(nome='Opcional ' + str(t), grupo=grup, valor='1,00', disponivel=True) opc.save() foto_p = FotoProduto(produto=prod, url='http://placehold.it/150x150') foto_p.save() forma_entrega = FormaEntrega(estabelecimento=loja, forma='MOTOBOY') forma_entrega.save() f_p = FormaPagamento(estabelecimento=loja, forma='DINHEIRO') f_p.save() f_pag = FormaPagamento(estabelecimento=loja, forma='CREDITO', cartao='MASTERCARD') f_pag.save() return redirect('/')
def get_price(product, shop_id): """Launch price gen with config parameters Args: product ([Product]): Product at DB shop_id (int): shop identifier Returns: [float]: Finish price """ mom_selector = Configuration.get_value(shop_id, "MOM_SELECTOR", product.category_path) margin_percent = Configuration.get_value(shop_id, "MARGIN_PERCENT", product.category_path) if mom_selector: round_to = Configuration.get_value(shop_id, "ROUND_TO", product.category_path) mom_price = get_mom_price(product.sku) if mom_price is not None: return price_generator( purchase_price=product.price, margin=margin_percent, mom_price=mom_price, mom=True, round_to=round_to, ) return price_generator( product.price, margin=margin_percent, )
def info(): """Get App Info""" import json from app.models import Product, Shop, Configuration all_products = Product.query shops = {s.id: s.name for s in Shop.query.all()} data = { "Vida products:": all_products.count(), "New products:": all_products.filter(Product.is_new == True # noqa E712 ).count(), "Changed products:": all_products.filter(Product.is_changed == True).count(), "Deleted products:": all_products.filter(Product.is_deleted == True).count(), } csv_check_sum = Configuration.get_common_value("CSV_CHECK_SUM") if csv_check_sum: data["CSV check sum:"] = csv_check_sum vida_updated = Configuration.get_common_value("LAST_VIDAXL_PROD_UPDATED") if vida_updated: data["Last VidaXl Products updated: %s"] = str(vida_updated) if shops: data["Shops:"] = shops print(json.dumps( data, indent=2, ))
def save_all_configurations(): data = request.get_json() configs_data = data['configurations'] for config_data in configs_data: config = Configuration() config.key = config_data['key'] config.value = config_data['value'] db.session.add(config) db.session.commit() return jsonify(configs_data), 201
def mainupdate(): for d in Device.query.all(): for c in d.configurations: c.delete() run_file = "data/" + d.name + "-run.txt" route_file = "data/" + d.name + "-route.txt" version_file = "data/" + d.name + "-version.txt" run_configuration = Configuration(path=run_file, device=d) route_configuration = Configuration(path=route_file, device=d) version_configuration = Configuration(path=version_file, device=d) run_configuration.save() route_configuration.save() version_configuration.save() runpath = re.compile('.*run.txt') routepath = re.compile('.*route.txt') versionpath = re.compile('.*version.txt') # Ouais ok je delete tout, mais on n'a pas vraiment le choix et je vous emmerde for c in ConfigurationValues.query.all(): c.delete() for c in DeviceInterfaces.query.all(): c.delete() for c in DeviceRoutes.query.all(): c.delete() for conf in Configuration.query.all(): cversion = versionpath.match(conf.path) crun = runpath.match(conf.path) croute = routepath.match(conf.path) if cversion: for lines in open(conf.path): lines = lines.strip() cisco_search = re.search('(?i)Cisco\sIOS.*,.*\((\w+\d*)-.*\).*Version\s(\d*.\d*)\(.*', lines) if cisco_search: model_version = cisco_search.group(1) version_version = cisco_search.group(2) ConfigurationValues(version=version_version, model=model_version, configuration_id=conf.id).save() if crun: int_regex = re.compile('(?i)interface\s(.*)\n ip address (.*) (.*)\n.*\n (?!shutdown)', re.MULTILINE) with open(conf.path) as runfile: for match in int_regex.finditer(runfile.read()): interface_run = match.group(1) ip_run = match.group(2) mask_run = match.group(3) DeviceInterfaces(name=interface_run, addr=ip_run, netmask=mask_run, configuration_id=conf.id).save() if croute: routeregex = re.compile('\w\**\s*(\d+.\d+.\d+.\d+)/*(\d+)*.*(connected|via),*\s+(.*)', re.MULTILINE) with open(conf.path) as runfile: for match in routeregex.finditer(runfile.read()): net_route = match.group(1) mask_route = match.group(2) gw_route = match.group(4) if match.group(3)=="connected": conn_route = 1 else: conn_route = 0 DeviceRoutes(net_dst=net_route, net_mask=mask_route, gw=gw_route, connected=conn_route, configuration_id=conf.id).save()
def add_data_db(): configurations = Configuration.query.all() for conf in configurations: db.session.delete(conf) db.session.commit() for dict_conf in available_configurations(): conf = Configuration(**dict_conf) db.session.add(conf) db.session.commit()
def post(self): args = configuration_parser.parse_args() if Configuration.query.filter_by(name=args.name).first(): return jsonify('A configuration already exists with that name.') configuration = Configuration( name=args.name, value=args.value, ) db.session.add(configuration) db.session.commit() return jsonify(marshal(configuration, configuration_fields))
def add_configuration(user, dict_conf): result = {'Data': None, 'Error': False, 'TextError': ''} if Configuration.query.filter((Configuration.project == dict_conf['project']) | ( Configuration.description == dict_conf['description'])).first() is None: del dict_conf['id'] conf = Configuration(**dict_conf) db.session.add(conf) db.session.commit() result['Data'] = conf.id else: result['Error'] = True result['TextError'] = 'Конфигурация с подобными полями уже существует' return result
def viewconfig(): form = ConfigurationForm() if form.is_submitted(): configuration = Configuration(name=form.name.data, \ description=form.description.data, \ type='custom', services=form.services.data, \ livestream_connected=0, \ user=current_user) db.session.add(configuration) db.session.commit() return redirect(url_for("main.viewconfig")) configurations = Configuration.query.filter_by( id_user=current_user.get_id()).all() return render_template('pages/placeholder.viewconfig.html', configurations=configurations, form=form)
def configuration(): form = ConfigurationForm() if form.validate_on_submit(): config = Configuration(config_name=form.config_name.data, username=form.username.data, password=form.password.data, hostname=form.hostname.data, database=form.database.data, port=form.port.data, dialect=form.dialect.data) db.session.add(config) db.session.commit() # keep this redirect here for a bit till I figure out what to do # with it return redirect(url_for('index')) return render_template('configuration.html', form=form)
def start(): log('START') if Configuration.query.first() is None: log('save setting_configurations') for dict_conf in setting_configurations(): conf = Configuration(**dict_conf) db.session.add(conf) db.session.commit() log('load configurations') configurations = Configuration.query.filter_by(active=True).all() for conf in configurations: data_release = current_configuration_release(conf) if data_release is None: continue try: add_release(conf, data_release) except Exception as ex: log(str(ex)) log('END')
def fill_db_by_test_data(): shop = Shop(name="Test Shop").save() images = [ "https://vdxl.im/8718475964735_a_en_hd_1.jpg", "https://vdxl.im/8718475964735_g_en_hd_1.jpg", "https://vdxl.im/8718475964735_g_en_hd_2.jpg", "https://vdxl.im/8718475964735_g_en_hd_3.jpg", "https://vdxl.im/8718475964735_g_en_hd_4.jpg", ] categories = [ "Toys & Games/Toys/Kids Riding Vehicles/Push & Pedal Riding Vehicles", "Animals & Pet Supplies/Pet Supplies/Cat Supplies/Cat Beds", "Animals & Pet Supplies/Pet Supplies/Dog Supplies/Dog Apparel", "Animals & Pet Supplies/Pet Supplies/Dog Supplies/Dog Beds", ] description = "<p>This memory foam neck pillow will surely bring you" description += "a soft velvety feel and a comfortable sleeping experience at home." description += "</p><ul><li>Colour: White<br/></li><li>Dimensions: 50 x 30 x (7-10) cm (L x W x H)<br/></li>" description += "<li>Delivery includes 2 pcs of pillow</li><li>Fabric: Polyester: 100%</li></ul>(product_id: 2899)" for i in range(10): Product(sku=f"{100089 + i}", title=f"Test Product({i + 1})", category_path=categories[i % len(categories)], price=((i + 1) * 1.01), qty=i + 1, vidaxl_id=35084 + i, description=description).save(commit=False) Image(product_id=i + 1, url=randint(0, len(images))).save(commit=False) Category(shop_id=shop.id, path=categories[1]).save(commit=False) Category(shop_id=shop.id, path=categories[2]).save(commit=False) Configuration.set_value(shop_id=shop.id, name='MARGIN_PERCENT', value='20', path=categories[0]) Configuration.set_value(shop_id=shop.id, name='ROUND_TO', value='95', path=categories[1]) Configuration.set_value(shop_id=shop.id, name='LEAVE_VIDAXL_PREFIX', value=True, path=categories[2]) db.session.commit()
#!/usr/bin/env python from app import db from app.models import Configuration, User from config import Config config = Config() admin = User() admin.set_password(config.ADMIN_PASSWORD) admin.username = "******" admin.name = "Administrateur" db.session.add(admin) db.session.commit() c = Configuration() c.config_key = "num_tel" c.config_text = "Numéro de contact" c.config_order = 1 db.session.add(c) c = Configuration() c.config_key = "mail_contact" c.config_text = "Email de contact" c.config_order = 2 db.session.add(c) c = Configuration() c.config_key = "mail_cantine" c.config_text = "E-mail des personnes qui recoivent les réservations de cantine" c.config_order = 3 db.session.add(c)
return derror if q == 2: child.sendline('terminal length 0') elif q == 3: derror[device.name] = 'wrong enable password' return derror q = child.expect(generate_pexpect_list([PROMPT_REGEX_CISCOENABLE])) for key in ComCiscoISR: if perror(device, derror, q): return derror if q == 2: child.sendline(key) q = child.expect(generate_pexpect_list([PROMPT_REGEX_CISCOENABLE])) path = get_path(device, key) with open(path, 'wb') as fd: fd.write(child.before) PasswordManager.encrypt_file(path, pwdh) conf = Configuration() conf.path = path conf.device_id = device.id conf.date = datetime.now() db.session.add(conf) db.session.commit() child.sendline('exit') print(derror) return derror else: derror[device.name] = device.method + ' not supported' print(derror) return derror
def load_configurations(self): for configuration in Configuration.objects(): self.load_configuration(configuration)
def apply_parameters(node, path): for name in PARAMETERS: if name not in node: log(log.ERROR, "apply_parameters no value of [%s]", name) continue Configuration.set_value(shop_id, name, node[name], path)
def add_parameters(node, path): for name in PARAMETERS: node[name] = Configuration.get_value(shop_id, name, path)
def set_up_timers_form(number_timers): error = None number_timers = int(number_timers) attribute_dict = { 'name': None, 'hours': None, 'minutes': None, 'seconds': None } for timer in range(number_timers): for attribute_name in attribute_dict: attribute = "timer_{}_{}".format(timer, attribute_name) if attribute_name == 'name': setattr(SetUpTimers, attribute, StringField(attribute, validators=[DataRequired()])) else: setattr( SetUpTimers, attribute, StringField( attribute, validators=[ DataRequired(), Regexp("^(\d?[0-9]|[0-9]0)$", message='must be whole number between 1-99') ])) form = SetUpTimers() object_list = [] for timer in range(number_timers): form_dict = attribute_dict.copy() for attribute_name in attribute_dict: attribute = "timer_{}_{}".format(timer, attribute_name) form_dict[attribute_name] = getattr(form, attribute) object_list.append(form_dict) if form.validate_on_submit(): user = User.query.filter_by(id=current_user.get_id()).first() if Configuration.query.filter_by( name=form.configuration.data).first() != None: error = 'Configuration with same name already exits' else: configuration = Configuration(name=form.configuration.data, user=user) db.session.add(configuration) db.session.commit() arg_dict = attribute_dict.copy() for form_dict in object_list: for key in arg_dict: arg_dict[key] = getattr(form_dict[key], "data") if not key == 'name': if len(arg_dict[key]) == 1: arg_dict[key] = "0" + arg_dict[key] timer = Timer(name=arg_dict['name'], hours=arg_dict['hours'], minutes=arg_dict['minutes'], seconds=arg_dict['seconds'], configuration=configuration) db.session.add(timer) db.session.commit() return redirect( url_for('timer_array', configuration=configuration.name)) return render_template('set_up_timers_form.html', logged_in=current_user.is_authenticated, form=form, timer=timer, object_list=object_list, error=error)
def set_csv_url(csv_url: str): Configuration.set_value(shop_id=1, name="CSV_URL", value=csv_url)
def get_csv_url() -> str: return Configuration.get_value(shop_id=1, name="CSV_URL")