Best Python code snippet using lemoncheesecake
sellable_product_consummer.py
Source:sellable_product_consummer.py
...22 Convert time to database time because when get datetime from database we subtracted 7h in BaseTimeStamp of model23 """24 base_time = data - timedelta(hours=7)25 return base_time.strftime('%Y-%m-%d %H:%M:%S.%f')26def _format_json(data, default_value=None):27 return json.dumps(data, ensure_ascii=False) if data else default_value28def _init_default(fields):29 response = {}30 for f in fields:31 response[f] = None32 return response33def _get_tax(tax):34 if tax == 'KT' or tax == '00':35 return 036 return safe_cast(tax, int)37def _get_selling_status(sellable_product):38 status = sellable_product.selling_status_code39 if sellable_product.is_bundle and status == 'active':40 status = 'hang_ban'41 elif not status:42 status = 'hang_dat_truoc'43 return status, _MAP_STATUS.get(status, 8)44def _get_editing_status(sellable_product):45 return sellable_product.editing_status_code46def _get_publish_status(sellable_product):47 return 1 if sellable_product.editing_status_code in ('active', 'editing') else 048def _get_need_manage_stock():49 # Now, always set to 150 return 151def _get_status(sellable_product):52 selling_status, priority = _get_selling_status(sellable_product)53 editing_status = _get_editing_status(sellable_product)54 publish_status = _get_publish_status(sellable_product)55 need_manage_stock = _get_need_manage_stock()56 return {57 'selling_status_code': selling_status,58 'editing_status': editing_status,59 'publish_status': publish_status,60 'need_manage_stock': need_manage_stock,61 'priority': priority,62 }63def _get_display_name(seo, advanced_info):64 if seo and seo.display_name:65 return seo.display_name66 seo_config = advanced_info.get('config_seo') or {}67 return seo_config.get('seo_name') or ''68def _get_smart_showroom(advanced_info):69 default_seo = advanced_info.get('default_seo') or {}70 return default_seo.get('smart_showroom') or ''71def _get_seo_by_field(seo, seo_config, field):72 if seo:73 value = getattr(seo, field)74 if value:75 return value76 return seo_config.get(field) or ''77def _get_master_categories(categories):78 response = []79 for c in categories:80 response.append({81 'id': c.id,82 'code': c.code,83 'name': c.name,84 'level': c.depth,85 'parent_id': c.parent_id,86 })87 return response88def _get_categories(categories):89 def _format(item):90 return {91 'id': item.id,92 'code': item.code,93 'name': item.name,94 'level': item.depth,95 'parent_id': item.parent_id,96 'is_adult': item.is_adult97 }98 response = []99 for cat in categories:100 response.append({101 'platform_id': cat.get('platform_id'),102 'owner_seller_id': cat.get('seller_id'),103 'categories': list(map(lambda c: _format(c), cat.get('platform_categories')))})104 return response105def _get_config_seo(seo, advanced_info):106 seo_config = advanced_info.get('config_seo') or {}107 return {108 'meta_keyword': _get_seo_by_field(seo, seo_config, 'meta_keyword'),109 'short_description': _get_seo_by_field(seo, seo_config, 'short_description'),110 'description': _get_seo_by_field(seo, seo_config, 'description'),111 'meta_title': _get_seo_by_field(seo, seo_config, 'meta_title'),112 'meta_description': _get_seo_by_field(seo, seo_config, 'meta_description'),113 }114class ProductDetail:115 def __init__(self, session):116 self.session = session117 def __get_seller(self, sellable_product):118 seller = self.session.query(m.Seller).filter(m.Seller.id == sellable_product.seller_id).first()119 if seller:120 return {121 'id': seller.id,122 'name': seller.name,123 'display_name': seller.display_name,124 }125 return _init_default(('id', 'name', 'display_name'))126 def __get_seo(self, sellable_product):127 seo = self.session.query(m.SellableProductSeoInfoTerminal).filter(128 m.SellableProductSeoInfoTerminal.sellable_product_id == sellable_product.id).first()129 return seo130 def __get_url_key(self, seo, sellable_product):131 if seo and seo.url_key:132 return seo.url_key133 variant = self.session.query(m.ProductVariant).filter(134 m.ProductVariant.id == sellable_product.variant_id).first()135 return variant.url_key if variant else ''136 def __get_product_type(self, sellable_product):137 misc = self.session.query(m.Misc).filter(m.Misc.type == 'product_type',138 m.Misc.code == sellable_product.product_type).first()139 if misc:140 return {141 'code': misc.code,142 'name': misc.name,143 }144 return {145 'code': 'product',146 'name': 'Sản phẩm váºt lý'147 }148 def __get_images(self, sellable_product):149 images = self.session.query(m.VariantImage).filter(150 m.VariantImage.product_variant_id == sellable_product.variant_id,151 m.VariantImage.status == 1, m.VariantImage.is_displayed == 1152 ).order_by(m.VariantImage.priority).all()153 response = []154 for img in images:155 response.append({156 'url': img.url,157 'path': img.path or '',158 'priority': img.priority,159 'label': img.label,160 })161 return response162 def __get_color(self, sellable_product):163 color = self.session.query(m.Color).filter(m.Color.id == sellable_product.color_id).first()164 if color:165 return {166 'code': color.code,167 'name': color.name,168 }169 return None170 def __get_barcodes(self, sellable_product):171 barcodes = self.session.query(m.SellableProductBarcode). \172 filter(m.SellableProductBarcode.sellable_product_id == sellable_product.id).all()173 return barcodes174 def __get_category_tree(self, sellable_product):175 sku_categories = self.session.query(m.ProductCategory).filter(176 m.ProductCategory.product_id == sellable_product.product_id).all()177 leaf_category_ids = list(map(lambda x: x.category_id, sku_categories))178 leaf_categories = self.session.query(m.Category).filter(m.Category.id.in_(leaf_category_ids)) \179 .order_by(m.Category.depth, m.Category.path).all()180 seller_ids = list(map(lambda x: x.seller_id, leaf_categories))181 platforms = self.session.query(m.PlatformSellers).filter(m.PlatformSellers.seller_id.in_(seller_ids),182 m.PlatformSellers.is_owner.is_(True)).all()183 ids = []184 root_ids = {}185 for cat in leaf_categories:186 platform_category_ids = list(map(lambda x: safe_cast(x, int), filter(lambda x: x, cat.path.split('/'))))187 root_ids[cat.seller_id] = platform_category_ids[0]188 ids.extend(platform_category_ids)189 all_categories = self.session.query(m.Category).filter(m.Category.id.in_(ids)) \190 .order_by(m.Category.depth, m.Category.path).all()191 categories = []192 for platform in platforms:193 platform_categories = list(filter(lambda x: x.seller_id == platform.seller_id, all_categories))194 categories.append({'platform_id': platform.platform_id, 'seller_id': platform.seller_id,195 'platform_categories': platform_categories})196 return categories197 def __get_master_category_tree(self, sellable_product):198 if not sellable_product.master_category_id:199 return []200 cat = self.session.query(m.MasterCategory).filter(201 m.MasterCategory.id == sellable_product.master_category_id).first()202 ids = list(map(lambda x: safe_cast(x, int), filter(lambda x: x, cat.path.split('/'))))203 return self.session.query(m.MasterCategory).filter(m.MasterCategory.id.in_(ids)) \204 .order_by(m.MasterCategory.depth, m.MasterCategory.path).all()205 def __get_attribute_set(self, sellable_product):206 attribute_set = self.session.query(m.AttributeSet).filter(207 m.AttributeSet.id == sellable_product.attribute_set_id).first()208 if attribute_set:209 return {210 'id': attribute_set.id,211 'name': attribute_set.name,212 }213 return _init_default(('id', 'name'))214 def __get_brand(self, sellable_product):215 brand = self.session.query(m.Brand).filter(m.Brand.id == sellable_product.brand_id).first()216 if brand:217 return {218 'id': brand.id,219 'code': brand.code,220 'name': brand.name,221 'description': ''222 }223 return _init_default(('code', 'name'))224 def __get_shipping_types(self, sellable_product):225 shipping_types = self.session.query(226 m.ShippingType227 ).join(228 m.SellableProductShippingType,229 m.SellableProductShippingType.shipping_type_id == m.ShippingType.id230 ).filter(m.SellableProductShippingType.sellable_product_id == sellable_product.id).all()231 return list(map(lambda x: x.code, shipping_types))232 def __get_sellable_product_by_sku(self, sku):233 return self.session.query(m.SellableProduct).filter(m.SellableProduct.sku == sku).first()234 def __get_sellable_product_bundle(self, sellable_product_id):235 query = self.session.query(m.SellableProduct).filter(236 m.SellableProduct.id == sellable_product_id).options(load_only('sku', 'name'))237 return query.first()238 def __get_bundles(self, sellable_product):239 sku_id = sellable_product.id240 bundles = self.session.query(m.SellableProductBundle).filter(241 or_(m.SellableProductBundle.bundle_id == sku_id,242 m.SellableProductBundle.sellable_product_id == sku_id)).all()243 response = {}244 for b in bundles:245 if b.bundle_id == sku_id:246 child = self.__get_sellable_product_bundle(b.sellable_product_id)247 if child:248 response['bundle_products'] = {249 'sku': child.sku,250 'quantity': b.quantity,251 'priority': b.priority,252 'name': child.name,253 'seo_name': None254 }255 elif b.sellable_product_id == sku_id:256 parent = self.__get_sellable_product_bundle(b.bundle_id)257 if parent:258 response['parent_bundles'] = {259 'sku': parent.sku,260 'name': parent.name,261 }262 return response263 def __get_tags(self, sellable_product):264 tag = self.session.query(m.SellableProductTag).filter(265 m.SellableProductTag.sellable_product_id == sellable_product.id).first()266 if not tag or not tag.tags:267 return []268 tags = tag.tags.split(',')269 return list(filter(lambda x: x, tags))270 def __get_advanced_info(self, sellable_product):271 advanced = AdvancedInfo(self.session)272 return advanced.get_advanced_info(sellable_product)273 def init_product_detail_v2(self, sku, updated_by):274 sellable_product = self.__get_sellable_product_by_sku(sku)275 if not sellable_product:276 return {}277 categories = self.__get_category_tree(sellable_product)278 master_categories = self.__get_master_category_tree(sellable_product)279 bundles = self.__get_bundles(sellable_product)280 images = self.__get_images(sellable_product)281 color = self.__get_color(sellable_product)282 seo = self.__get_seo(sellable_product)283 advanced_info = self.__get_advanced_info(sellable_product)284 barcodes = self.__get_barcodes(sellable_product)285 response = {286 'sku': sellable_product.sku,287 'seller_sku': sellable_product.seller_sku,288 'uom_code': sellable_product.uom_code,289 'uom_name': sellable_product.uom_name,290 'uom_ratio': sellable_product.uom_ratio,291 'seller_id': sellable_product.seller_id,292 'seller': _format_json(self.__get_seller(sellable_product)),293 'provider': _format_json({294 'id': sellable_product.provider_id295 }),296 'name': sellable_product.name,297 'url': self.__get_url_key(seo, sellable_product),298 'type': _format_json(self.__get_product_type(sellable_product)),299 'barcode': sellable_product.barcode,300 'barcodes': json.dumps([{'barcode': barcode.barcode,301 'source': barcode.source,302 'is_default': barcode.is_default} for barcode in barcodes]),303 'tax': _format_json({304 'tax_out_code': sellable_product.tax_out_code,305 'tax_in_code': sellable_product.tax_in_code,306 'tax_out': _get_tax(sellable_product.tax_out_code),307 'tax_in': _get_tax(sellable_product.tax_in_code),308 }),309 'images': _format_json(images),310 'display_name': _get_display_name(seo, advanced_info),311 'color': _format_json(color) if color else None,312 'product_line': '{}',313 'channels': None,314 'attribute_set': _format_json(self.__get_attribute_set(sellable_product)),315 'attributes': _format_json(advanced_info.get('attributes')),316 'categories': '[]',317 'platform_categories': _format_json(_get_categories(categories)),318 'seller_categories': _format_json(_get_master_categories(master_categories)),319 'brand': _format_json(self.__get_brand(sellable_product)),320 'status': _format_json(_get_status(sellable_product)),321 'smart_showroom': _get_smart_showroom(advanced_info),322 'seo_info': _format_json(_get_config_seo(seo, advanced_info)),323 'warranty': _format_json({324 'months': sellable_product.warranty_months,325 'description': sellable_product.warranty_note326 }),327 'sku_created_at': _format_json_datetime(sellable_product.created_at),328 'bundle_products': _format_json(bundles.get('bundle_products')) if bundles else None,329 'parent_bundles': _format_json(bundles.get('parent_bundles')) if bundles else None,330 'tags': _format_json(self.__get_tags(sellable_product), '[]'),331 'is_bundle': sellable_product.is_bundle,332 'attribute_groups': _format_json(advanced_info.get('attribute_groups')),333 'product_group': _format_json(advanced_info.get('product_group')),334 'serial_managed': sellable_product.tracking_type,335 'serial_generated': sellable_product.auto_generate_serial,336 'manufacture': _format_json(advanced_info.get('manufacture')),337 'shipping_types': _format_json(self.__get_shipping_types(sellable_product)),338 'updated_by': updated_by339 }...
cli.py
Source:cli.py
...54 List all accounts, services and dates.55 """56 cost = ctx.obj['client']57 if resource_type == 'accounts':58 print(utils._format_json(cost.list_accounts(account_type)))59 elif resource_type == 'services':60 print(utils._format_json(cost.list_service()))61 elif resource_type == 'dates':62 print(utils._format_json(cost.list_months(account_type)))63@cost.command('current')64@click.option('-t',65 '--account-type',66 default='AWS-Account',67 help='The type to get the cost for [default: AWS-Account]')68@click.option('-d',69 '--by-days',70 default=False,71 is_flag=True,72 help='Get current cost by days')73@click.option('-S',74 '--by-service',75 default=False,76 is_flag=True,77 help='Get current cost by service')78@click.option('-i',79 '--instance',80 default=False,81 is_flag=True,82 help='Get current cost for instances only')83@click.option('-n',84 '--account-name',85 help='The account to get the cost for')86@click.option('-id',87 '--report_id',88 help='Get current cost of perspective group from a report This only works in 2 dimensions reports')89@click.pass_context90def current_cost(ctx, account_type, by_days, by_service, instance, account_name, report_id):91 """Retrieve current cost for all accounts.92 Using the -S flag will get you a list of current services costs.93 Specifying an account name will get the current cost for that account only.94 Specifying an account type will get the cost to all accounts of that type.95 Omitting both will get the total cost of all accounts.96 Specifying a report id will get you the current cost based on filter and grouping done in web console97 """98 cost = ctx.obj['client']99 if instance:100 print(cost.get_cost_for_instances())[utils._get_yesterdays_date()]101 elif by_days:102 print(cost.get_current_by_days())[utils._get_yesterdays_date()]103 elif by_service:104 print(utils._format_json(cost.get_current_by_services()))105 elif report_id:106 print(utils._format_json(cost.get_custom_report(report_id)))107 elif account_name:108 print(cost.get_current_by_accounts(account_type, account_name)[account_name])109 else:110 print(utils._format_json(cost.get_current_by_accounts(account_type, account_name)))111@cost.command('account-history')112@click.option('-t',113 '--account-type',114 default='AWS-Account',115 help='The type to get the cost for [default: AWS-Account]')116@click.option('-n',117 '--account-name',118 help='The account to get the cost for')119@click.option('-m',120 '--month',121 # default=utils._get_last_month,122 help='Sum of cost for the last month [default: Last Month]')123@click.pass_context124def account_history(ctx, account_type, account_name, month):125 """Retrieve cost history by account.126 Specifying an account name will get the cost for the previous month.127 Specifying an account type will get the cost to all accounts of that type.128 Omitting both will get the total cost for previous month.129 """130 cost = ctx.obj['client']131 if account_name and month:132 full_history = cost.account_history(account_type)[month]133 print full_history[account_name]134 elif account_name:135 full_history = cost.account_history(account_type)136 for each_month, account in full_history.iteritems():137 print each_month, account[account_name]138 elif month:139 full_history = cost.account_history(account_type)[month]140 for name, amount in full_history.iteritems():141 print name, amount142 else:143 full_history = cost.account_history(account_type)144 print(utils._format_json(full_history))145@cost.command('service-history')146@click.option('-t',147 '--account-type',148 default='AWS-Account',149 help='The type to get the cost for [default: AWS-Account]')150@click.option('-i',151 '--instance',152 default=False,153 is_flag=True,154 help='Get current cost for instances only')155@click.option('-s',156 '--service',157 help='The service to get the cost for')158@click.option('-m',159 '--month',160 # default=utils._get_last_month,161 help='Sum of cost for the last month [default: Last Month]')162@click.pass_context163def service_history(ctx, account_type, service, month, instance):164 """Retrieve cost history by service.165 Specifying a service will get the cost for the previous month.166 Specifying a service and month will get the cost for the month and service.167 Omitting both will get a dict of services cost for previous month.168 """169 cost = ctx.obj['client']170 if month and service:171 full_history = cost.service_history()[month]172 print service, full_history[service]173 elif service:174 full_history = cost.service_history()175 for each_month, service_cost in full_history.iteritems():176 print each_month, service_cost[service]177 elif month:178 full_history = cost.service_history()[month]179 for each_month, service_cost in full_history.iteritems():180 print each_month, service_cost181 elif instance:182 print(utils._format_json(cost.get_cost_for_instances()))183 else:184 full_history = cost.service_history()185 print(utils._format_json(full_history))186@_cloudhealth.group(context_settings=CLICK_CONTEXT_SETTINGS, cls=DYMGroup)187@click.pass_context188def usage(ctx):189 """Retrieve resource usage related information190 """191 ctx.obj['client'] = ctx.obj['client'].usage192@usage.command('list')193@click.option('-t',194 '--account-type',195 default='AWS-Account',196 help='The type to get the cost for [default: AWS-Account]')197@click.pass_context198def list_services(ctx, account_type):199 """Retrieve list of usage resources200 """201 usage = ctx.obj['client']202 print(utils._format_json(usage.list_services(account_type)))203@usage.command('get')204@click.argument('resource-type')205@click.option('-d',206 '--date',207 default=utils._get_yesterdays_date,208 help='Resource usage per day [defaults to yesterday]')209@click.pass_context210def get_usage(ctx, resource_type, date):211 """Retrieve usage statistics by day and resource type.212 Specifying Date will get you the usage for that day.213 Specifying Resource type will get you the usage for a particular resources by date.214 Omitting date will get you the usage for yesterday.215 """216 usage = ctx.obj['client']217 if date == 'all':218 print(usage.get(resource_type=resource_type, date=date))219 elif date:220 print(usage.get(resource_type=resource_type, date=date)[date])221 else:222 print(usage.get(resource_type=resource_type, date=utils._get_yesterdays_date))223@_cloudhealth.group(context_settings=CLICK_CONTEXT_SETTINGS, cls=DYMGroup)224@click.pass_context225def reports(ctx):226 """Retrieve report related information227 """228 ctx.obj['client'] = ctx.obj['client'].reports229@reports.command('list')230@click.option('-t',231 '--topic',232 help='The topic to get the reports for')233@click.pass_context234def list_reports(ctx, topic):235 """List all reports236 Specifying a topic will get the reports only for that topic.237 """238 reports = ctx.obj['client']239 reports_list = reports.list(topic)240 for report in reports_list:241 print(report)242@reports.command('list-topics')243@click.pass_context244def list_topics(ctx):245 """List all topics246 """247 reports = ctx.obj['client']248 topics_list = reports.topics()249 for topic in topics_list:250 print(topic)251@reports.command(name='get')252@click.option('-i',253 '--id',254 default=None,255 help='The ID of the report')256@click.option('-t',257 '--topic',258 default=None,259 help='The topic of the report')260@click.option('-n',261 '--report-name',262 default=None,263 help='The name of the report')264@click.pass_context265def get_report(ctx, id, topic, report_name):266 """Retrieve a specific report267 """268 reports = ctx.obj['client']269 print(reports.get(id, topic, report_name))270@_cloudhealth.group(context_settings=CLICK_CONTEXT_SETTINGS, cls=DYMGroup)271@click.pass_context272def assets(ctx):273 """Retrieve assets related information274 """275 ctx.obj['client'] = ctx.obj['client'].assets276@assets.command(name='list')277@click.pass_context278def list_assets(ctx):279 """List all assets280 """281 assets = ctx.obj['client']282 assets_list = assets.list()283 for asset in assets_list:284 print(asset)285@assets.command(name='get')286@click.argument('object-name')287@click.pass_context288def get_asset(ctx, object_name):289 """Retrieve a specific asset.290 """291 assets = ctx.obj['client']292 # print(utils._format_json(assets.get(object_name)))293 print(utils._format_json(assets.get(object_name)))294@_cloudhealth.group(context_settings=CLICK_CONTEXT_SETTINGS, cls=DYMGroup)295@click.pass_context296def accounts(ctx):297 """Retrieve accounts related information298 """299 ctx.obj['client'] = ctx.obj['client'].accounts300@accounts.command(name='list')301@click.option('-t',302 '--account-type',303 default='AWS-Account',304 help='The type to get the cost for [default: AWS-Account]')305@click.pass_context306def list_accounts(ctx, account_type):307 accounts = ctx.obj['client']...
test.py
Source:test.py
...6 url_type = 'person_url'7 input_json = json.loads(requests.get(url).text)8 if type(input_json)==list:9 url_type = 'list_of_persons_url'10 return self._format_json(input_json, url_type)11 def _format_json(self, input_json, url_type):12 if url_type == "person_url":13 return {14 "full_name": input_json['full_name'],15 "job_title": input_json['job_title'],16 "profile_url": input_json["profile_url"],17 "location": input_json['location'],18 "email": input_json['email'],19 "phone_number": input_json['phone_number']20 }21 elif url_type == "list_of_persons_url":22 list_of_persons = []23 for person in input_json:24 list_of_persons.append({25 "full_name": person['full_name'],26 "profile_url": person['profile_url']27 })28 return list_of_persons29class Company():30 def get(self, url):31 url_type = 'company_url'32 input_json = json.loads(requests.get(url).text)33 if type(input_json) == list:34 url_type = 'list_of_companies_url'35 return self._format_json(input_json, url_type)36 def _format_json(self, input_json, url_type):37 if url_type == "company_url":38 leads = []39 for item in input_json['employees']:40 url = 'http://127.0.0.1:8000/employee/' + str(item)41 lead = Lead()42 result = lead.get(url)43 leads.append(result)44 return {45 "name": input_json['name'],46 "company_url": input_json['company_url'],47 "location": input_json["location"],48 "revenue": input_json['revenue'],49 "leads": leads50 }...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!