def do(): identity_loader, load_calls = id_loader() a, b = Promise.all([identity_loader.load("A"), identity_loader.load("B")]).get() assert a == "A" assert b == "B" assert load_calls == [["A", "B"]] a2, c = Promise.all( [identity_loader.load("A"), identity_loader.load("C")] ).get() assert a2 == "A" assert c == "C" assert load_calls == [["A", "B"], ["C"]] a3, b2, c2 = Promise.all( [ identity_loader.load("A"), identity_loader.load("B"), identity_loader.load("C"), ] ).get() assert a3 == "A" assert b2 == "B" assert c2 == "C" assert load_calls == [["A", "B"], ["C"]]
def test_promise_all_if(): p1 = Promise() p2 = Promise() pd1 = Promise.all([p1, p2]) pd2 = Promise.all([p1]) pd3 = Promise.all([]) assert p1.is_pending assert p2.is_pending assert pd1.is_pending assert pd2.is_pending assert pd3.is_fulfilled p1.fulfill(5) assert p1.is_fulfilled assert p2.is_pending assert pd1.is_pending assert pd2.is_fulfilled p2.fulfill(10) assert p1.is_fulfilled assert p2.is_fulfilled assert pd1.is_fulfilled assert pd2.is_fulfilled assert 5 == p1.value assert 10 == p2.value assert 5 == pd1.value[0] assert 5 == pd2.value[0] assert 10 == pd1.value[1] assert [] == pd3.value
def test_promise_all_if(): p1 = Promise() p2 = Promise() pd1 = Promise.all([p1, p2]) pd2 = Promise.all([p1]) pd3 = Promise.all([]) pd3._wait() assert p1.is_pending assert p2.is_pending assert pd1.is_pending assert pd2.is_pending assert pd3.is_fulfilled p1.do_resolve(5) p1._wait() pd2._wait() assert p1.is_fulfilled assert p2.is_pending assert pd1.is_pending assert pd2.is_fulfilled p2.do_resolve(10) p2._wait() pd1._wait() pd2._wait() assert p1.is_fulfilled assert p2.is_fulfilled assert pd1.is_fulfilled assert pd2.is_fulfilled assert 5 == p1.get() assert 10 == p2.get() assert 5 == pd1.get()[0] assert 5 == pd2.get()[0] assert 10 == pd1.get()[1] assert [] == pd3.get()
def test_issue_9(): no_wait = Promise.all( [promise_with_wait(x1, None).then(lambda y: x1 * y) for x1 in (0, 1, 2, 3)] ).get() wait_a_bit = Promise.all( [promise_with_wait(x2, 0.05).then(lambda y: x2 * y) for x2 in (0, 1, 2, 3)] ).get() wait_longer = Promise.all( [promise_with_wait(x3, 0.1).then(lambda y: x3 * y) for x3 in (0, 1, 2, 3)] ).get() assert no_wait == wait_a_bit assert no_wait == wait_longer
def do(): deep_loader, deep_load_calls = id_loader() a_loader, a_load_calls = id_loader( resolve=lambda keys: deep_loader.load(tuple(keys)) ) b_loader, b_load_calls = id_loader( resolve=lambda keys: deep_loader.load(tuple(keys)) ) a1, b1, a2, b2 = Promise.all( [ a_loader.load("A1"), b_loader.load("B1"), a_loader.load("A2"), b_loader.load("B2"), ] ).get() assert a1 == "A1" assert b1 == "B1" assert a2 == "A2" assert b2 == "B2" assert a_load_calls == [["A1", "A2"]] assert b_load_calls == [["B1", "B2"]] assert deep_load_calls == [[("A1", "A2"), ("B1", "B2")]]
def do(): identity_loader, load_calls = id_loader() a, b = Promise.all([identity_loader.load("A"), identity_loader.load("B")]).get() assert a == "A" assert b == "B" assert load_calls == [["A", "B"]] identity_loader.clear_all() a2, b2 = Promise.all( [identity_loader.load("A"), identity_loader.load("B")] ).get() assert a2 == "A" assert b2 == "B" assert load_calls == [["A", "B"], ["A", "B"]]
def do(): identity_loader, load_calls = id_loader() identity_loader.prime("A", "A") a, b = Promise.all([identity_loader.load("A"), identity_loader.load("B")]).get() assert a == "A" assert b == "B" assert load_calls == [["B"]]
def test_promise_all_follows_indifentely(): promises = Promise.all( [ Promise.resolve("A"), Promise.resolve(None) .then(Promise.resolve) .then(lambda v: Promise.resolve(None).then(lambda v: Promise.resolve("B"))), ] ) assert promises.get() == ["A", "B"]
def do(): identity_loader, load_calls = id_loader() promise1 = identity_loader.load(1) promise2 = identity_loader.load(2) p = Promise.all([promise1, promise2]) value1, value2 = p.get() assert value1 == 1 assert value2 == 2 assert load_calls == [[1, 2]]
def do(): identity_loader, load_calls = id_loader(max_batch_size=2) promise1 = identity_loader.load(1) promise2 = identity_loader.load(2) promise3 = identity_loader.load(3) p = Promise.all([promise1, promise2, promise3]) value1, value2, value3 = p.get() assert value1 == 1 assert value2 == 2 assert value3 == 3 assert load_calls == [[1, 2], [3]]
def test_promise_all_when_mixed_promises(): p1 = Promise() p2 = Promise() pl = Promise.all([p1, 32, p2, False, True]) assert p1.is_pending assert p2.is_pending assert pl.is_pending p1.fulfill(5) assert p1.is_fulfilled assert p2.is_pending assert pl.is_pending p2.fulfill(10) assert p1.is_fulfilled assert p2.is_fulfilled assert pl.is_fulfilled assert 5 == p1.value assert 10 == p2.value assert pl.value == [5, 32, 10, False, True]
def test_promise_all_when(): p1 = Promise() p2 = Promise() pl = Promise.all([p1, p2]) assert p1.is_pending assert p2.is_pending assert pl.is_pending p1.fulfill(5) assert p1.is_fulfilled assert p2.is_pending assert pl.is_pending p2.fulfill(10) assert p1.is_fulfilled assert p2.is_fulfilled assert pl.is_fulfilled assert 5 == p1.value assert 10 == p2.value assert 5 == pl.value[0] assert 10 == pl.value[1]
def complete_list_value(exe_context, return_type, field_asts, info, result): """ Complete a list value by completing each item in the list with the inner type """ assert isinstance(result, collections.Iterable), \ ('User Error: expected iterable, but did not find one ' + 'for field {}.{}.').format(info.parent_type, info.field_name) item_type = return_type.of_type completed_results = [] contains_promise = False for item in result: completed_item = complete_value_catching_error(exe_context, item_type, field_asts, info, item) if not contains_promise and is_promise(completed_item): contains_promise = True completed_results.append(completed_item) return Promise.all(completed_results) if contains_promise else completed_results
def test_promise_all_when_mixed_promises(): p1 = Promise() p2 = Promise() pl = Promise.all([p1, 32, p2, False, True]) assert p1.is_pending assert p2.is_pending assert pl.is_pending p1.do_resolve(5) p1._wait() assert p1.is_fulfilled assert p2.is_pending assert pl.is_pending p2.do_resolve(10) p2._wait() pl._wait() assert p1.is_fulfilled assert p2.is_fulfilled assert pl.is_fulfilled assert 5 == p1.get() assert 10 == p2.get() assert pl.get() == [5, 32, 10, False, True]
def test_promise_all_when(): p1 = Promise() p2 = Promise() pl = Promise.all([p1, p2]) assert p1.is_pending assert p2.is_pending assert pl.is_pending p1.do_resolve(5) p1._wait() assert p1.is_fulfilled assert p2.is_pending assert pl.is_pending p2.do_resolve(10) p2._wait() pl._wait() assert p1.is_fulfilled assert p2.is_fulfilled assert pl.is_fulfilled assert 5 == p1.get() assert 10 == p2.get() assert 5 == pl.get()[0] assert 10 == pl.get()[1]
def resolver(obj, args, context, info): inputs = args[arg_name] return Promise.all([ resolve_single_input(input, context, info) for input in inputs ])
def test_promise_all_when_if_no_promises(): pl = Promise.all([10, 32, False, True]) assert pl.get() == [10, 32, False, True]
def test_promise_all_when_if_no_promises(): pl = Promise.all([10, 32, False, True]) assert pl.is_fulfilled assert pl.value == [10, 32, False, True]
def subscribe(self, query, operation_name, callback, variables, context, format_error, format_response): parsed_query = parse(query) rules = specified_rules + [SubscriptionHasSingleRootField] errors = validate(self.schema, parsed_query, rules=rules) if errors: return Promise.rejected(ValidationError(errors)) args = {} subscription_name = '' for definition in parsed_query.definitions: if isinstance(definition, OperationDefinition): root_field = definition.selection_set.selections[0] subscription_name = root_field.name.value fields = self.schema.get_subscription_type().fields for arg in root_field.arguments: arg_definition = [ arg_def for _, arg_def in fields.get( subscription_name).args.iteritems() if arg_def.out_name == arg.name.value ][0] args[arg_definition.out_name] = value_from_ast( arg.value, arg_definition.type, variables=variables) if self.setup_funcs.get(to_snake_case(subscription_name)): trigger_map = self.setup_funcs[to_snake_case(subscription_name)]( query=query, operation_name=operation_name, callback=callback, variables=variables, context=context, format_error=format_error, format_response=format_response, args=args, subscription_name=subscription_name) else: trigger_map = {} trigger_map[subscription_name] = {} external_subscription_id = self.max_subscription_id self.max_subscription_id += 1 self.subscriptions[external_subscription_id] = [] subscription_promises = [] for trigger_name in trigger_map.viewkeys(): try: channel_options = trigger_map[trigger_name].get( 'channel_options', {}) filter = trigger_map[trigger_name].get('filter', lambda arg1, arg2: True) # TODO: Think about this some more...the Apollo library # let's all messages through by default, even if # the users incorrectly uses the setup_funcs (does not # use 'filter' or 'channel_options' keys); I think it # would be better to raise an exception here except AttributeError: channel_options = {} def filter(arg1, arg2): return True def on_message(root_value): def context_promise_handler(result): if isinstance(context, FunctionType): return context() else: return context def filter_func_promise_handler(context): return Promise.all([context, filter(root_value, context)]) def context_do_execute_handler(result): context, do_execute = result if not do_execute: return else: return execute(self.schema, parsed_query, root_value, context, variables, operation_name) return Promise.resolve(True).then( context_promise_handler).then( filter_func_promise_handler).then( context_do_execute_handler).then( lambda result: callback(None, result)).catch( lambda error: callback(error, None)) subscription_promises.append( self.pubsub.subscribe( trigger_name, on_message, channel_options).then(lambda id: self.subscriptions[ external_subscription_id].append(id))) return Promise.all(subscription_promises).then( lambda result: external_subscription_id)
def with_checkout_lines(results): checkouts, checkout_lines = results variants_pks = list({ line.variant_id for lines in checkout_lines for line in lines }) if not variants_pks: return [[] for _ in keys] channel_pks = [checkout.channel_id for checkout in checkouts] def with_variants_products_collections(results): ( variants, products, product_types, collections, channel_listings, voucher_infos, ) = results variants_map = dict(zip(variants_pks, variants)) products_map = dict(zip(variants_pks, products)) product_types_map = dict(zip(variants_pks, product_types)) collections_map = dict(zip(variants_pks, collections)) channel_listings_map = dict( zip(variant_ids_channel_ids, channel_listings)) lines_info_map = defaultdict(list) voucher_infos_map = { voucher_info.voucher.code: voucher_info for voucher_info in voucher_infos if voucher_info } for checkout, lines in zip(checkouts, checkout_lines): lines_info_map[checkout.pk].extend([ CheckoutLineInfo( line=line, variant=variants_map[line.variant_id], channel_listing=channel_listings_map[( line.variant_id, checkout.channel_id)], product=products_map[line.variant_id], product_type=product_types_map[line.variant_id], collections=collections_map[line.variant_id], ) for line in lines ]) for checkout in checkouts: if not checkout.voucher_code: continue voucher_info = voucher_infos_map.get(checkout.voucher_code) if not voucher_info: continue voucher = voucher_info.voucher if (voucher.type == VoucherType.SPECIFIC_PRODUCT or voucher.apply_once_per_order): apply_voucher_to_checkout_line( voucher_info=voucher_info, checkout=checkout, lines_info=lines_info_map[checkout.pk], discounts=self.context.discounts, ) return [lines_info_map[key] for key in keys] variants = ProductVariantByIdLoader( self.context).load_many(variants_pks) products = ProductByVariantIdLoader( self.context).load_many(variants_pks) product_types = ProductTypeByVariantIdLoader( self.context).load_many(variants_pks) collections = CollectionsByVariantIdLoader( self.context).load_many(variants_pks) voucher_codes = { checkout.voucher_code for checkout in checkouts if checkout.voucher_code } voucher_infos = VoucherInfoByVoucherCodeLoader( self.context).load_many(voucher_codes) variant_ids_channel_ids = [] for channel_id, lines in zip(channel_pks, checkout_lines): variant_ids_channel_ids.extend([(line.variant_id, channel_id) for line in lines]) channel_listings = VariantChannelListingByVariantIdAndChannelIdLoader( self.context).load_many(variant_ids_channel_ids) return Promise.all([ variants, products, product_types, collections, channel_listings, voucher_infos, ]).then(with_variants_products_collections)
def submit_all(tasks): return Promise.all([(task.submit() if isinstance(task, Task) else task) for task in tasks])
def with_checkout_lines(results): checkouts, checkout_lines = results variants_pks = list({ line.variant_id for lines in checkout_lines for line in lines }) if not variants_pks: return [[] for _ in keys] channel_pks = [checkout.channel_id for checkout in checkouts] def with_variants_products_collections(results): ( variants, products, product_types, collections, channel_listings, ) = results variants_map = dict(zip(variants_pks, variants)) products_map = dict(zip(variants_pks, products)) product_types_map = dict(zip(variants_pks, product_types)) collections_map = dict(zip(variants_pks, collections)) channel_listings_map = dict( zip(variant_ids_channel_ids, channel_listings)) lines_info_map = defaultdict(list) for checkout, lines in zip(checkouts, checkout_lines): lines_info_map[checkout.pk].extend([ CheckoutLineInfo( line=line, variant=variants_map[line.variant_id], channel_listing=channel_listings_map[( line.variant_id, checkout.channel_id)], product=products_map[line.variant_id], product_type=product_types_map[line.variant_id], collections=collections_map[line.variant_id], ) for line in lines ]) return [lines_info_map[key] for key in keys] variants = ProductVariantByIdLoader( self.context).load_many(variants_pks) products = ProductByVariantIdLoader( self.context).load_many(variants_pks) product_types = ProductTypeByVariantIdLoader( self.context).load_many(variants_pks) collections = CollectionsByVariantIdLoader( self.context).load_many(variants_pks) variant_ids_channel_ids = [] for channel_id, lines in zip(channel_pks, checkout_lines): variant_ids_channel_ids.extend([(line.variant_id, channel_id) for line in lines]) channel_listings = VariantChannelListingByVariantIdAndChannelIdLoader( self.context).load_many(variant_ids_channel_ids) return Promise.all([ variants, products, product_types, collections, channel_listings ]).then(with_variants_products_collections)
def create_promise(): # unnecessary function call return Promise.all(values)
def with_channel(channels): billing_address_ids = { checkout.billing_address_id for checkout in checkouts if checkout.billing_address_id } shipping_address_ids = { checkout.shipping_address_id for checkout in checkouts if checkout.shipping_address_id } addresses = AddressByIdLoader( self.context).load_many(billing_address_ids | shipping_address_ids) users = UserByUserIdLoader(self.context).load_many([ checkout.user_id for checkout in checkouts if checkout.user_id ]) shipping_method_ids = [ checkout.shipping_method_id for checkout in checkouts if checkout.shipping_method_id ] shipping_methods = ShippingMethodByIdLoader( self.context).load_many(shipping_method_ids) shipping_method_ids_channel_slugs = [ (checkout.shipping_method_id, channel.slug) for checkout, channel in zip(checkouts, channels) if checkout.shipping_method_id ] shipping_method_channel_listings = ( ShippingMethodChannelListingByShippingMethodIdAndChannelSlugLoader( self.context).load_many( shipping_method_ids_channel_slugs)) def with_checkout_info(results): ( addresses, users, shipping_methods, channel_listings, ) = results address_map = { address.id: address for address in addresses } user_map = {user.id: user for user in users} shipping_method_map = { shipping_method.id: shipping_method for shipping_method in shipping_methods } shipping_method_channel_listing_map = { (listing.shipping_method_id, listing.channel_id): listing for listing in channel_listings } checkout_info_map = {} for key, checkout, channel in zip(keys, checkouts, channels): checkout_info_map[key] = CheckoutInfo( checkout=checkout, user=user_map.get(checkout.user_id), channel=channel, billing_address=address_map.get( checkout.billing_address_id), shipping_address=address_map.get( checkout.shipping_address_id), shipping_method=shipping_method_map.get( checkout.shipping_method_id), valid_shipping_methods=[], shipping_method_channel_listings=( shipping_method_channel_listing_map.get( (checkout.shipping_method_id, channel.id)), ), ) return [checkout_info_map[key] for key in keys] return Promise.all([ addresses, users, shipping_methods, shipping_method_channel_listings, ]).then(with_checkout_info)
from promise import Promise promise = Promise (lambda resolve, reject: 2) a = promise.then() print(a.value) def test_rest(res): return res == ['a', 'b', 'c'] p = Promise.all([Promise.resolve('a'), 'b', Promise.resolve('c')]) \ .then(test_rest) print(p.value) assert p.value is True p = Promise.resolve('a') print(p.value) def promessaHandler(resolve, reject): return reject('RESOLVIDO!') p = Promise(promessaHandler) print(p.value)
def resolver(_obj, info, **args): inputs = args[arg_name] return Promise.all( [resolve_single_input(info, input_) for input_ in inputs])
def with_channel(channels): billing_address_ids = { checkout.billing_address_id for checkout in checkouts if checkout.billing_address_id } shipping_address_ids = { checkout.shipping_address_id for checkout in checkouts if checkout.shipping_address_id } addresses = AddressByIdLoader( self.context).load_many(billing_address_ids | shipping_address_ids) users = UserByUserIdLoader(self.context).load_many([ checkout.user_id for checkout in checkouts if checkout.user_id ]) shipping_method_ids = [ checkout.shipping_method_id for checkout in checkouts if checkout.shipping_method_id ] shipping_methods = ShippingMethodByIdLoader( self.context).load_many(shipping_method_ids) channel_slugs = [channel.slug for channel in channels] shipping_method_channel_listings = ( ShippingMethodChannelListingByChannelSlugLoader( self.context).load_many(channel_slugs)) collection_point_ids = [ checkout.collection_point_id for checkout in checkouts if checkout.collection_point_id ] collection_points = WarehouseByIdLoader( self.context).load_many(collection_point_ids) def with_checkout_info(results): ( addresses, users, shipping_methods, listings_for_channels, collection_points, ) = results address_map = { address.id: address for address in addresses } user_map = {user.id: user for user in users} shipping_method_map = { shipping_method.id: shipping_method for shipping_method in shipping_methods } collection_points_map = { collection_point.id: collection_point for collection_point in collection_points } checkout_info_map = {} for key, checkout, channel, checkout_lines in zip( keys, checkouts, channels, checkout_line_infos): shipping_method = shipping_method_map.get( checkout.shipping_method_id) collection_point = collection_points_map.get( checkout.collection_point_id) shipping_address = address_map.get( checkout.shipping_address_id) delivery_method_info = get_delivery_method_info( None, shipping_address) checkout_info = CheckoutInfo( checkout=checkout, user=user_map.get(checkout.user_id), channel=channel, billing_address=address_map.get( checkout.billing_address_id), shipping_address=address_map.get( checkout.shipping_address_id), delivery_method_info=delivery_method_info, valid_pick_up_points=[], all_shipping_methods=[], ) manager = self.context.plugins discounts = self.context.discounts shipping_method_listings = [ listing for channel_listings in listings_for_channels for listing in channel_listings if listing.channel_id == channel.id ] update_delivery_method_lists_for_checkout_info( checkout_info, shipping_method, collection_point, shipping_address, checkout_lines, discounts, manager, shipping_method_listings, ) checkout_info_map[key] = checkout_info return [checkout_info_map[key] for key in keys] return Promise.all([ addresses, users, shipping_methods, shipping_method_channel_listings, collection_points, ]).then(with_checkout_info)
def batch_load(self, keys): def with_pages_and_assigned_attributes(result): pages, page_attributes = result assigned_page_attributes_ids = list( {attr.id for attrs in page_attributes for attr in attrs}) page_type_ids = [page.page_type_id for page in pages] page_attributes = dict(zip(keys, page_attributes)) def with_attribute_pages_and_values(result): attribute_pages, attribute_values = result attribute_ids = list( {ap.attribute_id for aps in attribute_pages for ap in aps}) attribute_pages = dict(zip(page_type_ids, attribute_pages)) attribute_values = dict( zip(assigned_page_attributes_ids, attribute_values)) def with_attributes(attributes): id_to_attribute = dict(zip(attribute_ids, attributes)) selected_attributes_map = defaultdict(list) for key, page in zip(keys, pages): assigned_pagetype_attributes = attribute_pages[ page.page_type_id] assigned_page_attributes = page_attributes[key] for assigned_pagetype_attribute in assigned_pagetype_attributes: page_assignment = next( (apa for apa in assigned_page_attributes if apa.assignment_id == assigned_pagetype_attribute.id), None, ) attribute = id_to_attribute[ assigned_pagetype_attribute.attribute_id] if page_assignment: values = attribute_values[page_assignment.id] else: values = [] selected_attributes_map[key].append({ "values": values, "attribute": attribute }) return [selected_attributes_map[key] for key in keys] return (AttributesByAttributeId(self.context).load_many( attribute_ids).then(with_attributes)) attribute_pages = AttributePagesByPageTypeIdLoader( self.context).load_many(page_type_ids) attribute_values = AttributeValuesByAssignedPageAttributeIdLoader( self.context).load_many(assigned_page_attributes_ids) return Promise.all([attribute_pages, attribute_values ]).then(with_attribute_pages_and_values) pages = PageByIdLoader(self.context).load_many(keys) assigned_attributes = AssignedPageAttributesByPageIdLoader( self.context).load_many(keys) return Promise.all([pages, assigned_attributes ]).then(with_pages_and_assigned_attributes)
def submit_all(tasks, delay=0): return Promise.all([(task.submit_with_delay( i * delay * random.random()) if isinstance(task, Task) else task) for i, task in enumerate(tasks)])
def get_debug_promise(self): if not self.debug_promise: self.debug_promise = Promise.all(self.promises) return self.debug_promise.then(self.on_resolve_all_promises)
def get_image( self, loader: ImageLoader, width: int, height: int, bordered_sides: int = imageutils.ALL_SIDES, triangled = True, ) -> Image.Image: pictured_printings = self.sorted_imageds images = [ image.resize( ( width, image.height * width // image.width, ), Image.LANCZOS, ) if isinstance(image, Image.Image) and image.width != width else image for image in Promise.all( tuple( loader.get_image(option, crop = True) if isinstance(option, Printing) else Promise.resolve(option) for option in pictured_printings ) ).get() ] background = Image.new('RGBA', (width, height), (0, 0, 0, 255)) draw = ImageDraw.Draw(background) cx, cy, content_width, content_height = imageutils.shrunk_box( x = 0, y = 0, w = width, h = height, shrink = self._BORDER_WIDTH - 1, sides = bordered_sides, ) font_size = 27 + int(27 * min(width, self._FULL_WIDTH) / self._FULL_WIDTH) for span, option, image, in zip( imageutils.section(content_height, len(pictured_printings)), pictured_printings, images, ): start, stop = span if isinstance(option, Printing): background.paste( imageutils.fit_image(image, content_width, stop - start + 1), (cx, start + cy), ) imageutils.draw_name( draw = draw, name = self._name_printing(option), box = ( cx, start + cy, content_width, stop - start, ), font_path = self._FONT_PATH, font_size = font_size, ) else: background.paste( option.get_image( loader = loader, width = content_width, height = stop - start, bordered_sides = imageutils.LEFT_SIDE, triangled = True, ), (cx, start + cy), ) agg_draw = aggdraw.Draw(background) if triangled: imageutils.triangled_inlined_box( draw = agg_draw, box = (0, 0, width, height), color = self._BORDER_COLOR, bar_color = self._BORDER_TRIANGLE_COLOR, width = self._BORDER_WIDTH, triangle_length = self._BORDER_WIDTH, sides = bordered_sides, ) else: imageutils.inline_box( draw = agg_draw, box = (0, 0, width, height), color = self._BORDER_COLOR, width = self._BORDER_WIDTH, sides = bordered_sides, ) return background
def _resolve_thumbnail(result): product, variant_medias = result if image := _get_first_variant_image(variant_medias): return _get_image_from_media(image) # we failed to get image from variant, lets use first from product return (ProductImageByProductIdLoader(info.context).load( product.id).then(_get_first_product_image)) variants_product = ProductByVariantIdLoader(info.context).load( root.variant_id) variant_medias = MediaByProductVariantIdLoader(info.context).load( root.variant_id) return Promise.all([variants_product, variant_medias]).then(_resolve_thumbnail) @staticmethod def resolve_unit_price(root: models.OrderLine, _info): return root.unit_price @staticmethod def resolve_undiscounted_unit_price(root: models.OrderLine, _info): return root.undiscounted_unit_price @staticmethod def resolve_unit_discount_type(root: models.OrderLine, _info): return root.unit_discount_type @staticmethod def resolve_unit_discount_value(root: models.OrderLine, _info):
def filter_func_promise_handler(context): return Promise.all([context, filter(root_value, context)])
def resolve_available_shipping_methods(root: models.Checkout, info): def calculate_available_shipping_methods(data): address, lines, checkout_info, discounts, channel = data channel_slug = channel.slug display_gross = info.context.site.settings.display_gross_prices manager = info.context.plugins subtotal = manager.calculate_checkout_subtotal( checkout_info, lines, address, discounts) if not address: return [] available = get_valid_shipping_methods_for_checkout( checkout_info, lines, subtotal=subtotal, country_code=address.country.code, ) if available is None: return [] available_ids = available.values_list("id", flat=True) def map_shipping_method_with_channel(shippings): def apply_price_to_shipping_method(channel_listings): channel_listing_map = { channel_listing.shipping_method_id: channel_listing for channel_listing in channel_listings } available_with_channel_context = [] for shipping in shippings: shipping_channel_listing = channel_listing_map[ shipping.id] taxed_price = info.context.plugins.apply_taxes_to_shipping( shipping_channel_listing.price, address) if display_gross: shipping.price = taxed_price.gross else: shipping.price = taxed_price.net available_with_channel_context.append( ChannelContext(node=shipping, channel_slug=channel_slug)) return available_with_channel_context map_shipping_method_and_channel = ( (shipping_method_id, channel_slug) for shipping_method_id in available_ids) return ( ShippingMethodChannelListingByShippingMethodIdAndChannelSlugLoader( info.context).load_many( map_shipping_method_and_channel).then( apply_price_to_shipping_method)) return (ShippingMethodByIdLoader(info.context).load_many( available_ids).then(map_shipping_method_with_channel)) channel = ChannelByIdLoader(info.context).load(root.channel_id) address = (AddressByIdLoader(info.context).load( root.shipping_address_id) if root.shipping_address_id else None) lines = CheckoutLinesInfoByCheckoutTokenLoader(info.context).load( root.token) checkout_info = CheckoutInfoByCheckoutTokenLoader(info.context).load( root.token) discounts = DiscountsByDateTimeLoader(info.context).load( info.context.request_time) return Promise.all([address, lines, checkout_info, discounts, channel ]).then(calculate_available_shipping_methods)
def with_variants_and_assigned_attributed(results): product_variants, variant_attributes = results product_ids = list({v.product_id for v in product_variants}) assigned_variant_attribute_ids = [ a.id for attrs in variant_attributes for a in attrs ] variant_attributes = dict(zip(keys, variant_attributes)) def with_products_and_attribute_values(results): products, attribute_values = results product_type_ids = list({p.product_type_id for p in products}) products = dict(zip(product_ids, products)) attribute_values = dict( zip(assigned_variant_attribute_ids, attribute_values)) def with_attribute_products(attribute_products): attribute_ids = list({ ap.attribute_id for aps in attribute_products for ap in aps }) attribute_products = dict( zip(product_type_ids, attribute_products)) def with_attributes(attributes): id_to_attribute = dict(zip(attribute_ids, attributes)) selected_attributes_map = defaultdict(list) for key, product_variant in zip( keys, product_variants): product = products[product_variant.product_id] assigned_producttype_attributes = attribute_products[ product.product_type_id] assigned_variant_attributes = variant_attributes[ key] for (assigned_producttype_attribute ) in assigned_producttype_attributes: variant_assignment = next( (apa for apa in assigned_variant_attributes if apa.assignment_id == assigned_producttype_attribute.id), None, ) attribute = id_to_attribute[ assigned_producttype_attribute. attribute_id] if variant_assignment: values = attribute_values[ variant_assignment.id] else: values = [] selected_attributes_map[key].append({ "values": values, "attribute": attribute }) return [selected_attributes_map[key] for key in keys] return (AttributesByAttributeId(self.context).load_many( attribute_ids).then(with_attributes)) return (AttributeVariantsByProductTypeIdLoader( self.context).load_many(product_type_ids).then( with_attribute_products)) products = ProductByIdLoader(self.context).load_many(product_ids) attribute_values = AttributeValuesByAssignedVariantAttributeIdLoader( self.context).load_many(assigned_variant_attribute_ids) return Promise.all([products, attribute_values ]).then(with_products_and_attribute_values)
def _complete_transfer(self, transfer): promises = list(self.transfer_log.complete(transfer)) if not transfer['executionCondition']: promises.append(self.transfer_log.fulfill(transfer)) return Promise.all(promises)
def _splat_all(*promises): return Promise.all(promises)
def with_channel(channels): billing_address_ids = { checkout.billing_address_id for checkout in checkouts if checkout.billing_address_id } shipping_address_ids = { checkout.shipping_address_id for checkout in checkouts if checkout.shipping_address_id } addresses = AddressByIdLoader( self.context).load_many(billing_address_ids | shipping_address_ids) users = UserByUserIdLoader(self.context).load_many([ checkout.user_id for checkout in checkouts if checkout.user_id ]) shipping_method_ids = [ checkout.shipping_method_id for checkout in checkouts if checkout.shipping_method_id ] shipping_methods = ShippingMethodByIdLoader( self.context).load_many(shipping_method_ids) shipping_method_ids_channel_slugs = [ (checkout.shipping_method_id, channel.slug) for checkout, channel in zip(checkouts, channels) if checkout.shipping_method_id ] shipping_method_channel_listings = ( ShippingMethodChannelListingByShippingMethodIdAndChannelSlugLoader( self.context).load_many( shipping_method_ids_channel_slugs)) collection_point_ids = [ checkout.collection_point_id for checkout in checkouts if checkout.collection_point_id ] collection_points = WarehouseByIdLoader( self.context).load_many(collection_point_ids) def with_checkout_info(results): ( addresses, users, shipping_methods, channel_listings, collection_points, ) = results address_map = { address.id: address for address in addresses } user_map = {user.id: user for user in users} shipping_method_map = { shipping_method.id: shipping_method for shipping_method in shipping_methods } shipping_method_channel_listing_map = { (listing.shipping_method_id, listing.channel_id): listing for listing in channel_listings if listing } collection_points_map = { collection_point.id: collection_point for collection_point in collection_points } checkout_info_map = {} for key, checkout, channel in zip(keys, checkouts, channels): shipping_method = shipping_method_map.get( checkout.shipping_method_id) external_app_shipping_id = get_external_shipping_id( checkout) if shipping_method: delivery_method = convert_to_shipping_method_data( shipping_method) elif external_app_shipping_id: delivery_method = self.context.plugins.get_shipping_method( checkout=checkout, channel_slug=checkout.channel.slug, shipping_method_id=external_app_shipping_id, ) else: delivery_method = collection_points_map.get( checkout.collection_point_id) shipping_address = (address_map.get( checkout.shipping_address_id), ) delivery_method_info = get_delivery_method_info( delivery_method, shipping_address) checkout_info_map[key] = CheckoutInfo( checkout=checkout, user=user_map.get(checkout.user_id), channel=channel, billing_address=address_map.get( checkout.billing_address_id), shipping_address=address_map.get( checkout.shipping_address_id), delivery_method_info=delivery_method_info, valid_shipping_methods=[], valid_pick_up_points=[], shipping_method_channel_listings=( shipping_method_channel_listing_map.get( (checkout.shipping_method_id, channel.id))), ) return [checkout_info_map[key] for key in keys] return Promise.all([ addresses, users, shipping_methods, shipping_method_channel_listings, collection_points, ]).then(with_checkout_info)