def connection_resolver(cls, resolver, connection, default_manager, max_limit, enforce_first_or_last, root, args, context, info): first = args.get('first') last = args.get('last') if enforce_first_or_last: assert first or last, ( 'You must provide a `first` or `last` value to properly paginate the `{}` connection.' ).format(info.field_name) if max_limit: if first: assert first <= max_limit, ( 'Requesting {} records on the `{}` connection exceeds the `first` limit of {} records.' ).format(first, info.field_name, max_limit) args['first'] = min(first, max_limit) if last: assert last <= max_limit, ( 'Requesting {} records on the `{}` connection exceeds the `last` limit of {} records.' ).format(first, info.field_name, max_limit) args['last'] = min(last, max_limit) iterable = resolver(root, args, context, info) on_resolve = partial(cls.resolve_connection, connection, default_manager, args) if Promise.is_thenable(iterable): return Promise.resolve(iterable).then(on_resolve) return on_resolve(iterable)
def test_chained_promises(): """ Handles the case where the arguments to then are values, not functions or promises. """ p1 = Promise(lambda resolve, reject: resolve(Promise.resolve(True))) assert p1.get() == True
def execute(schema, document_ast, root_value=None, context_value=None, variable_values=None, operation_name=None, executor=None): assert schema, 'Must provide schema' assert isinstance(schema, GraphQLSchema), ( 'Schema must be an instance of GraphQLSchema. Also ensure that there are ' + 'not multiple versions of GraphQL installed in your node_modules directory.' ) if executor is None: executor = SyncExecutor() context = ExecutionContext( schema, document_ast, root_value, context_value, variable_values, operation_name, executor ) def executor(resolve, reject): return resolve(execute_operation(context, context.operation, root_value)) def on_rejected(error): context.errors.append(error) return None def on_resolve(data): return ExecutionResult(data=data, errors=context.errors) p = Promise(executor).catch(on_rejected).then(on_resolve) context.executor.wait_until_finished() return p.get()
def test_chain_with_promise(self): def worker_async(resolve_fn): sublime.set_timeout_async(lambda: resolve_fn(999), 100) def worker_async2(resolve_fn): sublime.set_timeout_async(lambda: resolve_fn(888), 100) def callback(async_value): self.assertEqual(async_value, 999) return Promise(worker_async2) def verify_async2_value(value): self.assertEqual(value, 888) promise = Promise(worker_async) self.assertFalse(promise._is_resolved()) promise2 = promise.then(callback) self.assertFalse(promise2._is_resolved()) promise2.then(verify_async2_value) # Let both promises resolve. time.sleep(0.500) self.assertTrue(promise._is_resolved()) self.assertEqual(promise._get_value(), 999) self.assertTrue(promise2._is_resolved()) self.assertEqual(promise2._get_value(), 888)
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_catch(): p1 = Promise(lambda resolve, reject: resolve(0)) p2 = p1.then(lambda value: 1 / value) \ .catch(lambda e: e) \ .then(lambda e: type(e)) assert p2.is_fulfilled assert p2.value == ZeroDivisionError
def connection_resolver( cls, resolver, connection, default_manager, max_limit, enforce_first_or_last, filterset_class, filters_name, root, info, **args, ): # Disable `enforce_first_or_last` if not querying for `edges`. values = [ field.name.value for field in info.field_asts[0].selection_set.selections ] if "edges" not in values: enforce_first_or_last = False first = args.get("first") last = args.get("last") if enforce_first_or_last: assert first or last, ( "You must provide a `first` or `last` value to properly " "paginate the `{}` connection." ).format(info.field_name) if max_limit: if first: assert first <= max_limit, ( "Requesting {} records on the `{}` connection exceeds the " "`first` limit of {} records." ).format(first, info.field_name, max_limit) args["first"] = min(first, max_limit) if last: assert last <= max_limit, ( "Requesting {} records on the `{}` connection exceeds the " "`last` limit of {} records." ).format(last, info.field_name, max_limit) args["last"] = min(last, max_limit) iterable = resolver(root, info, **args) on_resolve = partial(cls.resolve_connection, connection, default_manager, args) filter_input = args.get(filters_name) if filter_input and filterset_class: iterable = filterset_class( data=dict(filter_input), queryset=iterable, request=info.context ).qs if Promise.is_thenable(iterable): return Promise.resolve(iterable).then(on_resolve) return on_resolve(iterable)
def test_promise_loop(): def by_two(result): return result * 2 def executor(resolve, reject): resolve(Promise.resolve(1).then(lambda v: Promise.resolve(v).then(by_two))) p = Promise(executor) assert p.get(.1) == 2
def test_promise_reject_skip_all_other_values(): e1 = Exception("Error1") e2 = Exception("Error2") p = Promise() all_promises = all([1, Promise.reject(e1), Promise.reject(e2)]) with raises(Exception) as exc_info: all_promises.get() assert str(exc_info.value) == "Error1"
def test_resolve_promise_subclass(): class MyPromise(Promise): pass p = Promise() p.do_resolve(10) m_p = MyPromise.resolve(p) assert isinstance(m_p, MyPromise) assert m_p.get() == p.get()
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_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 test_chain_with_resolved(self): def worker(resolve_fn): resolve_fn(999) def assertResult(result): self.assertEqual(result, 999) promise = Promise(worker) self.assertTrue(promise._is_resolved()) promise2 = promise.then(assertResult) self.assertTrue(promise2._is_resolved())
def test_3_2_6_4_fulfilled(): """ Handles the case where the arguments to then are values, not functions or promises. """ p1 = Promise() p1.do_resolve(10) p2 = p1.then(5) assert 10 == p1.get() p2._wait() assert p2.is_fulfilled assert 10 == p2.get()
def test_3_2_6_5_rejected(): """ Handles the case where the arguments to then are values, not functions or promises. """ p1 = Promise() p1.do_reject(Exception("Error")) p2 = p1.then(None, 5) assert_exception(p1.reason, Exception, "Error") p2._wait() assert p2.is_rejected assert_exception(p2.reason, Exception, "Error")
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 test_promises_with_only_then(): context = {"success": False} error = RuntimeError("Ooops!") promise1 = Promise( lambda resolve, reject: context.update({"promise1_reject": reject}) ) promise2 = promise1.then(lambda x: None) promise3 = promise1.then(lambda x: None) context["promise1_reject"](error) promise2._wait() promise3._wait() assert promise2.reason == error assert promise3.reason == error
def test_chain_with_pending(self): def worker_async(resolve_fn): sublime.set_timeout_async(lambda: resolve_fn(999), 100) def assertResult(result): self.assertEqual(result, 999) promise = Promise(worker_async) self.assertFalse(promise._is_resolved()) promise2 = promise.then(assertResult) self.assertFalse(promise2._is_resolved()) # Let promises resolve. time.sleep(0.2) self.assertTrue(promise._is_resolved())
def test_3_2_6_1(): """ Promises returned by then must be fulfilled when the promise they are chained from is fulfilled IF the fulfillment value is not a promise. """ p1 = Promise.resolve(5) pf = p1.then(lambda v: v * v) assert pf.get() == 25 p2 = Promise.reject(Exception("Error")) pr = p2.then(None, lambda r: 5) assert 5 == pr.get()
def test_promise_follows_indifentely(): a = Promise.resolve(None) b = a.then(lambda x: Promise.resolve("X")) e = Event() def b_then(v): c = Promise.resolve(None) d = c.then(lambda v: Promise.resolve("B")) return d promise = b.then(b_then) assert promise.get() == "B"
def decider_local_activity_task(*args, **kwargs): """ Runs the activity task in decider-local mode. :param args: :param kwargs: :return: """ p = Promise() p.is_ready = True try: p.result = f(*args, **kwargs) except Exception as e: p.exception = e return p
def decider_local_child_workflow(*args, **kwargs): """ Treats this decision task as a child workflow within another decision task in a serial fashion. :param args: :param kwargs: :return: """ p = Promise() p.is_ready = True try: result = f(*args, **kwargs) p.result = result except Exception as e: p.exception = e return p
def test_promised_list_slice_respects_a_smaller_first(): letters_promise_slice = Promise.resolve(letters[:3]) c = connection_from_promised_list_slice( letters_promise_slice, dict(first=2), slice_start=0, list_length=5 ) expected = { 'edges': [ { 'node': 'A', 'cursor': 'YXJyYXljb25uZWN0aW9uOjA=', }, { 'node': 'B', 'cursor': 'YXJyYXljb25uZWN0aW9uOjE=', }, ], 'pageInfo': { 'startCursor': 'YXJyYXljb25uZWN0aW9uOjA=', 'endCursor': 'YXJyYXljb25uZWN0aW9uOjE=', 'hasPreviousPage': False, 'hasNextPage': True, } } assert c.value.to_dict() == expected
def testNonFunction(nonFunction): def foo(k, r): results[k] = r p1 = Promise.resolve("Error: " + str(nonFunction)) p2 = p1.then(lambda r: foo(str(nonFunction), r), nonFunction) p2._wait()
def execute(self, fn, *args, **kwargs): result = fn(*args, **kwargs) if isinstance(result, Future) or iscoroutine(result): future = ensure_future(result, loop=self.loop) self.futures.append(future) return Promise.resolve(future) return result
def execute_fields_serially(exe_context, parent_type, source_value, fields): def execute_field_callback(results, response_name): field_asts = fields[response_name] result = resolve_field( exe_context, parent_type, source_value, field_asts ) if result is Undefined: return results if is_thenable(result): def collect_result(resolved_result): results[response_name] = resolved_result return results return promisify(result).then(collect_result, None) results[response_name] = result return results def execute_field(prev_promise, response_name): return prev_promise.then(lambda results: execute_field_callback(results, response_name)) return functools.reduce(execute_field, fields.keys(), Promise.resolve(collections.OrderedDict()))
def testNonFunction(nonFunction): def foo(k, r): results[k] = r p1 = Promise.reject(Exception("Error: " + str(nonFunction))) p2 = p1.then(nonFunction, lambda r: foo(str(nonFunction), r)) p2._wait()
def wrapper(cls, root, info, password, **kwargs): def on_resolve(values): user, payload = values payload.token = get_token(user, info.context) return payload username = kwargs.get(get_user_model().USERNAME_FIELD) user = authenticate( request=info.context, username=username, password=password) if user is None: raise exceptions.GraphQLJWTError( _('Please, enter valid credentials')) if hasattr(info.context, 'user'): info.context.user = user result = f(cls, root, info, **kwargs) values = (user, result) # Improved mutation with thenable check if is_thenable(result): return Promise.resolve(values).then(on_resolve) return on_resolve(values)
def resolve(self, next, root, info, **kwargs): context = info.context result = next(root, info, **kwargs) return result.then( lambda resolved: self.__process_value(resolved, root, info, **kwargs), lambda error: Promise.rejected(error) )
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 resolve_total_price(root: models.Checkout, info): def calculate_total_price(data): address, lines, checkout_info, discounts = data taxed_total = (calculations.checkout_total( manager=info.context.plugins, checkout_info=checkout_info, lines=lines, address=address, discounts=discounts, ) - root.get_total_gift_cards_balance()) return max(taxed_total, zero_taxed_money(root.currency)) address_id = root.shipping_address_id or root.billing_address_id address = (AddressByIdLoader(info.context).load(address_id) if 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]).then(calculate_total_price)
def resolve_subtotal_price(root: models.Checkout, info): def calculate_subtotal_price(data): address, lines, checkout_info, discounts = data return calculations.checkout_subtotal( manager=info.context.plugins, checkout_info=checkout_info, lines=lines, address=address, discounts=discounts, ) address_id = root.shipping_address_id or root.billing_address_id address = ( AddressByIdLoader(info.context).load(address_id) if 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]).then( calculate_subtotal_price )
def resolve_shipping_address(root: models.Order, info): def _resolve_shipping_address(data): if isinstance(data, Address): user = None address = data else: user, address = data requester = get_user_or_app_from_context(info.context) if requestor_has_access(requester, user, OrderPermissions.MANAGE_ORDERS): return address return obfuscate_address(address) if not root.shipping_address_id: return if root.user_id: user = UserByUserIdLoader(info.context).load(root.user_id) address = AddressByIdLoader(info.context).load( root.shipping_address_id) return Promise.all([user, address]).then(_resolve_shipping_address) return (AddressByIdLoader(info.context).load( root.shipping_address_id).then(_resolve_shipping_address))
def diff_str(self): def decode_diff(results): encoding = self._get_view_encoding() try: decoded_results = results.decode(encoding.replace(' ', '')) except UnicodeError: try: decoded_results = results.decode("utf-8") except UnicodeDecodeError: decoded_results = "" except LookupError: try: decoded_results = codecs.decode(results) except UnicodeDecodeError: decoded_results = "" return decoded_results def run_diff(_unused): self.update_buf_file() args = [ settings.git_binary_path, 'diff', '-U0', '--no-color', '--no-index', settings.ignore_whitespace, settings.patience_switch, self.git_temp_file, self.buf_temp_file, ] args = list(filter(None, args)) # Remove empty args return GitGutterHandler.run_command(args).then(decode_diff) if self.on_disk() and self.git_path: return self.update_git_file().then(run_diff) else: return Promise.resolve("")
def map_variant_ids_with_channel(channel): def with_variants_products_collections(results): variants, products, collections, channel_listings = results variants_map = dict(zip(variants_pks, variants)) products_map = dict(zip(variants_pks, products)) collections_map = dict(zip(variants_pks, collections)) channel_listings_map = dict( zip(variants_pks, channel_listings)) lines_info = [] for lines in checkout_lines: lines_info.append([ CheckoutLineInfo( line=line, variant=variants_map[line.variant_id], channel_listing=channel_listings_map[ line.variant_id], product=products_map[line.variant_id], collections=collections_map[line.variant_id], ) for line in lines ]) return lines_info variants = ProductVariantByIdLoader( self.context).load_many(variants_pks) products = ProductByVariantIdLoader( self.context).load_many(variants_pks) collections = CollectionsByVariantIdLoader( self.context).load_many(variants_pks) variant_ids_channel_slug = [(variant_pk, channel.slug) for variant_pk in variants_pks] channel_listings = VariantChannelListingByVariantIdAndChannelSlugLoader( self.context).load_many(variant_ids_channel_slug) return Promise.all([ variants, products, collections, channel_listings ]).then(with_variants_products_collections)
def batch_load_fn(self, keys: 'List[Any]') -> Promise: """ Load related objects. Args: keys: Primary key values of parent model. Returns: Lists of related orm objects. """ query = self._get_query().filter( getattr(self.parent_model, self.parent_model_pk_field).in_(keys) ) # type: Query objects = { self.parent_model_object_to_key(parent_object): getattr( parent_object, self.model_relation_field ) for parent_object in query } # type: Dict[tuple, Any] return Promise.resolve( [objects.get(object_id, []) for object_id in keys] )
def with_channel(channel): address_id = checkout.shipping_address_id or checkout.billing_address_id address = (AddressByIdLoader(info.context).load(address_id) if address_id else None) variant = ProductVariantByIdLoader(info.context).load( root.variant_id) channel_listing = VariantChannelListingByVariantIdAndChannelSlugLoader( info.context).load((root.variant_id, channel.slug)) product = ProductByVariantIdLoader(info.context).load( root.variant_id) collections = CollectionsByVariantIdLoader(info.context).load( root.variant_id) discounts = DiscountsByDateTimeLoader(info.context).load( info.context.request_time) return Promise.all([ checkout, address, variant, channel_listing, product, collections, channel, discounts, ]).then(calculate_line_total_price)
def batch_load_fn(self, keys: List[BatchKeyType]) -> None: tags_index_args_map: MutableMapping[TagType, List[Tuple[int, UUIDType]]] = { } # noqa E501 for index, key in enumerate(keys): tag, args = key index_args_list = tags_index_args_map.get(tag, []) index_args_list.append((index, args)) tags_index_args_map[tag] = index_args_list index_resource_list: List[Tuple[int, Any]] = [] # type: ignore for tag in tags_index_args_map: index_args_list = tags_index_args_map[tag] index_resource_list.extend( TAG_TO_RESOURCES_GETTER_FUNCTION_MAP[tag]( index_args_list)) # noqa E502 return Promise.resolve([ resource[1] for resource in sorted(index_resource_list, key=lambda member: member[0]) ])
def putSeriesContent(self, session, seriesContent, publicKey): try: p = Promise() for i in seriesContent: enContent = myEncryption.aesEnctypt(i[2], i[1]) enkey = myEncryption.rsaEncrypt(i[2], publicKey) i[1] = enContent i[2] = enkey (rSpec, rRequest) = self.create("putseriescontent:securityproto", True) rRequest.session = session s = [] for i in seriesContent: j = self.createGeneric("Content:SecurityProto") j.name = i[0] j.content = i[1] j.key = i[2] s.append(j) rRequest.seriesContent = s self.send(self.serverId, self.proto, rSpec, rRequest, self._getRequestId(p)) return p except Exception as e: print e
def putKeys(self, session, key, contentIds, otherUserId, publicKey): try: p = Promise() enKey = {} for k, v in key.items(): enKey[k] = myEncryption.rsaEncrypt(v, publicKey) # newKey = myEncryption.rsaEncrypt(key,publicKey) # self.keyId = None kCIds = [] for k, v in contentIds.items(): kCId = self.createGeneric("KeyContentId:SecurityProto") kCId.key = enKey[k] kCId.contentId = v kCId.userId = otherUserId kCIds.append(kCId) (rSpec, rRequest) = self.create("putkeys:securityproto", True) rRequest.session = session rRequest.KeyContentIds = kCIds self.send(self.serverId, self.proto, rSpec, rRequest, self._getRequestId(p)) return p except Exception as e: print e
def getSeriesContent(self, session, contentIds, privateKey): try: p = Promise() (rSpec, rRequest) = self.create("getseriescontent:securityproto", True) rRequest.session = session cIds = [] for i in contentIds: cId = self.createGeneric("ConId:SecurityProto") cId.name = i[0] cId.contentId = i[1] cIds.append(cId) rRequest.contentIds = cIds def decrypt(enKey, enContent): key = myEncryption.rsaDecrypt(enKey, privateKey) content = myEncryption.aesDectypt(key, enContent) return content self.send(self.serverId, self.proto, rSpec, rRequest, self._getRequestId(p, decrypt)) return p except Exception as e: print e
def add_count(self, cls, args): # escape non-trivial cases defined in `authorization_filter` if cls != psqlgraph.Node and not hasattr(cls, 'project_id'): return None if cls.label == 'project': return None # escape if project_id is not the only args if list(args.keys()) != ['project_id']: return None # extract project_id and guarantee permission project_id = args['project_id'] if isinstance(project_id, (list, tuple)) and len(project_id) == 1: project_id = project_id[0] if not isinstance(project_id, (str, unicode)): # escape if multiple project_ids are given return None if project_id not in flask.g.read_access_projects: return 0 # group project_id and name them project_id_name = self._project_ids.get(project_id, None) if project_id_name is None: project_id_name = 'p_%s' % len(self._project_ids) self._project_ids[project_id] = project_id_name # prepare the subquery and promise key = 'c_%s' % len(self._queries) p = Promise() self._queries.append(( key, p, "(SELECT count(*) FROM %s WHERE _props->>'project_id' = :%s) AS %s" % (cls.__tablename__, project_id_name, key), )) return p
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))
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 index = 0 path = info.path[:] for item in result: info.path = path + [index] completed_item = complete_value_catching_error(exe_context, item_type, field_asts, info, item) if not contains_promise and is_thenable(completed_item): contains_promise = True completed_results.append(completed_item) index += 1 return Promise.all(completed_results) if contains_promise else completed_results
def handle_files(self, additional_args): if self.on_disk() and self.git_path: def is_nonempty(results): encoding = self._get_view_encoding() try: decoded_results = results.decode(encoding.replace(' ', '')) except UnicodeError: decoded_results = results.decode("utf-8") return (decoded_results != "") args = [ settings.git_binary_path, '--git-dir=' + self.git_dir, '--work-tree=' + self.git_tree, 'ls-files', '--other', '--exclude-standard', ] + additional_args + [ os.path.join(self.git_tree, self.git_path), ] args = list(filter(None, args)) # Remove empty args return GitGutterHandler.run_command(args).then(is_nonempty) return Promise.resolve(False)
def resolve_available_collection_points(root: models.Checkout, info): def get_available_collection_points(data): address, lines, channel = data if address: country_code = address.country.code else: country_code = channel.default_country.code return get_valid_collection_points_for_checkout( lines, country_code=country_code ) lines = CheckoutLinesInfoByCheckoutTokenLoader(info.context).load(root.token) channel = ChannelByIdLoader(info.context).load(root.channel_id) address = ( AddressByIdLoader(info.context).load(root.shipping_address_id) if root.shipping_address_id else None ) return Promise.all([address, lines, channel]).then( get_available_collection_points )
def wrapper(cls, root, info, password, **kwargs): context = info.context context._jwt_token_auth = True def on_resolve(values): user, payload = values payload.token = get_token(user, context) if jwt_settings.JWT_LONG_RUNNING_REFRESH_TOKEN: payload.refresh_token = refresh_token_lazy(user) return payload username = kwargs.get(get_user_model().USERNAME_FIELD) user = authenticate( request=context, username=username, password=password, ) if user is None: raise exceptions.JSONWebTokenError( _('Please, enter valid credentials')) if hasattr(context, 'user'): context.user = user result = f(cls, root, info, **kwargs) values = (user, result) signals.token_issued.send(sender=cls, request=context, user=user) if is_thenable(result): return Promise.resolve(values).then(on_resolve) return on_resolve(values)
def update(self): update_promises = dict() # create placeholder promises for each engine. is resolved if updated on all machines machine_update_promises = dict() for engine_class in self.engine_classes: engine = engine_class(self.cfg_parser) if engine.is_disabled(): continue machine_update_promises[engine.name] = [] update_promises[engine] = Promise(None) # create update promise update_promise = MultiActionPromise(update_promises) # call update on each machine for machine in self._machines: machine_update_promise = machine.update() # set callback post update to check if all engines on all machines are updated => if so, triggers resolve on update promise for engine, engine_update_promise in machine_update_promise._engine_promises.items( ): machine_update_promises[engine.name].append( engine_update_promise) engine_update_promise.then( lambda result: self. check_if_this_engine_is_updated_on_all_machines( result, machine_update_promises, update_promise), lambda result: self. check_if_this_engine_is_updated_on_all_machines( result, machine_update_promises, update_promise), ) return update_promise
def complete_list_value( exe_context, # type: ExecutionContext return_type, # type: GraphQLList field_asts, # type: List[Field] info, # type: ResolveInfo path, # type: List[Union[int, str]] result, # type: Any ): # type: (...) -> List[Any] """ Complete a list value by completing each item in the list with the inner type """ assert isinstance( result, 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 index = 0 for item in result: completed_item = complete_value_catching_error(exe_context, item_type, field_asts, info, path + [index], item) if not contains_promise and is_thenable(completed_item): contains_promise = True completed_results.append(completed_item) index += 1 return ( # type: ignore Promise.all(completed_results) if contains_promise else completed_results)
def resolve(self, next, *args, **kwargs): return Promise.resolve(next(*args, **kwargs))
def execute(self, fn, *args, **kwargs): promise = Promise() job = gevent.spawn(process, promise, fn, args, kwargs) self.jobs.append(job) return promise
def __execute_whoami(self, schandlerid): return (self.command_whoami(schandlerid=schandlerid) .then(lambda res: self.__set_schandler_data(schandlerid, res["clid"], res["cid"])) .then(lambda res: self.emit("connected-server", schandlerid)) # ignore error if not connected to ts server .catch(lambda err: None if err.id == 1794 else Promise.reject(err)))
def batch_load_fn(self, keys): load_calls.append(keys) return Promise.resolve(keys)
def __queue_command(self, command, input): promise = Promise(lambda resolve, reject: self.__command_queue.append( ClientQueryCommand(command, input, resolve, reject))) promise.then(lambda res: self.__on_command_done(), lambda err: self.__on_command_done()) self.__process_command_queue() return promise
def register_notify(self, name): assert name != "any" if name in self.__registered_events: return Promise.resolve(None) self.__registered_events.append(name) return self.command_clientnotifyregister(schandlerid=0, event=name)
def wrapped(cls, root, info, **kwargs): return Promise()
def get_release_managed(self, release_id: int) -> Promise[CubeRelease]: return Promise.resolve( self._executor.submit( self._get_release_managed, release_id, ))
def resolve(self, next, root, args, context, info): result = next(root, args, context, info) return result.then( lambda resolved: self.__process_value(resolved, root, args, context, info), lambda error: Promise.rejected(error) )
def batch_load_fn(self, keys): result_set = self.database.latest_meter_tariff_today() return Promise.resolve([ self.get_meter_tariff(result_set=result_set, key=key) for key in keys ])
def batch_load_fn(self, keys): result_set = self.database.all_meter_readings_between( self.__start, self.__end) return Promise.resolve([ get_meter_reading(result_set=result_set, key=key) for key in keys ])