def filter_brands_by_code(root, con_log, code): """Remove brands with brand code different than code. Removes BrandPrograms and adds an error message if there are no brands left. """ parent_map = get_parent_map(root) brands = [] brands_removed = 0 for brand in root.findall(anywhere('Brand')): brand_code = brand.findtext(add_xmlns('Code')) if brand_code != code: parent_map[brand].remove(brand) brands_removed += 1 else: brands.append(brand) if not brands: for program in root.findall(anywhere('BrandProgram')): parent_map[program].remove(program) mkt_response = root.find(anywhere('MarketResponse')) # TODO Update when BS team specify error message for no matching brands message = ET.SubElement(mkt_response, 'Message', messageCode='Warning', failCode='3001') message.text = 'No programs found' output = 'Filtered out {:d} non-{:s} brands, {:d} left'.format( brands_removed, code, len(brands)) con_log(log_category='plg_out', text=output) return root
def find_brands(root, brand_code=None): """ Returns all Brand nodes. If brand_code is set - returns only the brands with given Brand Code """ if brand_code is None: return root.findall(anywhere('Brand')) else: # [tag=smth] is an undocumented (or rater not clearly documented) feature # of ET but it works as expected return root.findall( anywhere('Brand[{:s}="{:s}"]'.format(add_xmlns('Code'), brand_code)))
def add_fake_t186_itemno(root, con_log, offset): """Add an itemno to each brand. The value of itemno = Brand/Tier + offset. """ updated_element_count = 0 for brand in root.findall(anywhere('Brand')): tier = brand.findtext(add_xmlns('Tier')) if tier: itemno = int(tier) + offset itemno_elem = ET.SubElement(brand, 'CarrierFlightItemNum') itemno_elem.text = str(itemno) updated_element_count += 1 output = 'Added itemno to {:d} elements'.format(updated_element_count) con_log(log_category='plg_out', text=output) return root
def add_fake_MarketDataSource(root, con_log, data_source, market_id=None): """ Add a fake dataSource attribute to all ProgramIdList elements""" updated_element_count = 0 if market_id: search_pattern = 'MarketResponse[@marketID="{:s}"]/'.format(market_id) search_pattern += add_xmlns('ProgramIdList') search_pattern = anywhere(search_pattern) else: search_pattern = anywhere('ProgramIdList') for program_list in root.findall(search_pattern): program_list.set('dataSource', data_source) updated_element_count += 1 output = 'Set dataSource for market {:s} to ' \ '"{:s}" in {:d} elements'.format(market_id or '*', data_source, updated_element_count) con_log(log_category='plg_out', text=output) return root
def find_brand_codes(root): return root.findall(anywhere('Brand/{}'.format(add_xmlns('Code'))))