async def wrap_handler(self, connection): self.listening_tasks.add(Task.current_task(self.loop)) try: await self.on_client_connect(connection) except CancelledError: pass except Exception as e: self.log.exception('caught unexpected exception: %s', e) self.clients.remove(connection) await connection.close() self.listening_tasks.remove(Task.current_task(self.loop))
def get(self, key): task = Task.current_task() try: context = task._context except AttributeError: return return context.get(key)
def __enter__(self): if self._timeout is None: return self self._task = Task.current_task(self._loop) tm = self._loop.time() + self._timeout self._cancel_handler = self._loop.call_at(tm, self._cancel_task) return self
async def _available_permanent(self): try: while not Task.current_task().cancelled(): self.mark_available() await sleep(30) except CancelledError: pass
def wrapped(loop, coro): parent_task = Task.current_task(loop=loop) child_task = task_factory(loop, coro) if child_task._source_traceback: del child_task._source_traceback[-1] context = getattr(parent_task, _TASK_CONTEXT_ATTR, {}) setattr(child_task, _TASK_CONTEXT_ATTR, dict(context)) return child_task
async def test_dispatch_event_cancel(self, source): """Test that dispatching an event when there are no listeners will still work.""" source.event_a.connect(lambda event: None) future = source.event_a.dispatch() future.cancel() task = next(t for t in Task.all_tasks() if t is not Task.current_task()) await task
def __getattr__(self, name): '''Prepend name name to standard logger functions''' #set_trace() if name in ('debug', 'info', 'warning', 'error', 'exception'): # task id by default nm=getattr(self, 'name', '{:04x}'.format(id(Task.current_task())%(1<<16))) return lambda msg: getattr(lg, name)('[{}] {}'.format(nm, msg))
def current(cls: Type[T]) -> T: """Return current context (creating it if necessary).""" local = Task.current_task() or _thread_local rv = getattr(local, 'ctx', None) if rv is None: # noinspection PyCallingNonCallable rv = local.ctx = cls() return rv
def get_component(type_: Type): """ Get a component based . :param type_: :return: """ current_task = Task.current_task() return current_task.components.get(type_)
def get_component(type_): """ :param type_: :return: """ current_task = Task.current_task() return current_task.components.get(type_)
def set(self, key, value): """Set a value in the task context """ task = Task.current_task() try: context = task._context except AttributeError: task._context = context = {} context[key] = value
async def _keep_alive(self, interval=10): while not Task.current_task().cancelled(): await sleep(interval) try: if await self.execute_command('ping') != 'pong': # TODO break except Exception as ex: self.logger.warning(ex)
def __curtask__(self): """ Create namespace in current task. """ task = Task.current_task(loop=self._loop) if not task: raise RuntimeError('No task is currently running') if not hasattr(task, '_locals'): task._locals = local_storage() return task._locals
def signal_handler(self): """Signal handler for asynchronous event loop Stops it gracefully """ with open("/dev/null") as sys.stderr: self._thread_executor.shutdown(wait=False) [task.cancel() for task in Task.all_tasks() if task is not Task.current_task()] self._event_loop.stop()
def _find_partition(loop): # find the partition by following the next strategies # 1 - Callback is called inside of a scope task # 2 - If not, use the ROOT_PARTITION try: return Task.current_task(loop=loop).partition except AttributeError: # out of a task scope return _ROOT_PARTITION
def issue_req_token(self, reply_fut, timeout): token = random_alphanumeric(6) while token in self.reply_inbox: token = random_alphanumeric(6) timer_handle = self._loop.call_later( timeout, partial(self.timeout_reply, token)) self.reply_inbox[token] = ReplyInboxItem(reply_fut, timer_handle, Task.current_task(self._loop)) return token
def issue_req_token(self, reply_fut, timeout): token = random_alphanumeric(6) while token in self.reply_inbox: token = random_alphanumeric(6) timer_handle = self._loop.call_later( timeout, partial(self.timeout_reply, token)) self.reply_inbox[token] = ReplyInboxItem( reply_fut, timer_handle, Task.current_task(self._loop)) return token
def stack_get(self, key): """Set a value in a task context stack """ task = Task.current_task() try: context = task._context_stack except AttributeError: return if key in context: return context[key][-1]
def get_component(type_): """ Gets the component of type `type_` :param `type_`: The `Type` of component to return :return: The component of type `type_` used in the current task. """ current_task = Task.current_task() return current_task.components.get(type_)
async def _setup_subscribe_protocol(self): local_address = ('0.0.0.0', self._port) try: self._subscribe_protocol = await create_subscribe_socket( local_address, loop=self._loop, timeout=self._timeout, message_callback=self._message_callback) except CancelledError: pass self._startup_tasks.remove(Task.current_task(loop=self._loop))
def stack_push(self, key, value): """Set a value in a task context stack """ task = Task.current_task() try: context = task._context_stack except AttributeError: task._context_stack = context = {} if key not in context: context[key] = [] context[key].append(value)
async def _setup_publish_protocol(self): local_address = ('0.0.0.0', 0) try: self._publish_protocol = await create_publish_socket( local_address, loop=self._loop, max_cache_size=self._max_cache_size, time_to_live=self._ttl) except CancelledError: pass self._startup_tasks.remove(Task.current_task(loop=self._loop))
async def cancel_tasks(): current = Task.current_task(self._aio_loop) tasks = [ task for task in Task.all_tasks(self._aio_loop) if task is not current ] for task in tasks: task.cancel() await asyncio.gather(*tasks)
async def __aenter__(self): task = Task.current_task() loop_time = task._loop.time() if self._absolute: self._secs = self._deadline - loop_time else: self._secs = self._deadline self._deadline += loop_time _set_task_deadline(task, self._deadline) self.expired = False self._task = task return self
def __call__(self, loop, coro): current = Task.current_task(loop=loop) task = Task(coro, loop=loop) try: task._context = current._context.copy() except AttributeError: pass try: task._context_stack = current._context_stack.copy() except AttributeError: pass return task
def identify_future(fut=None): """ Function to identify a task or future. :param fut: Future to identify. Optional. Default value is None. When it is None it use :meth:``asyncio.tasks.Task.current_task`` method. :type fut: asyncio.Future or None :return: int """ if fut is None: fut = Task.current_task() return id(fut)
def task(name=None, ndx=None): from asyncio import Task task_id = id(Task.current_task()) try: return TASK_MAP[task_id] except KeyError: if ndx is None: global CUR_TASK_ID CUR_TASK_ID += 1 ndx = CUR_TASK_ID TASK_MAP[task_id] = (ndx, name) return (ndx, name)
def stack_pop(self, key): """Remove a value in a task context stack """ task = Task.current_task() try: context = task._context_stack except AttributeError: raise KeyError('pop from empty stack') from None value = context[key] stack_value = value.pop() if not value: context.pop(key) return stack_value
async def start_get_updates(self): """ Starts get updates loop. """ await self.get_me() while not Task.current_task(self.loop).cancelled(): updates = await self.get_updates() for update in updates: if update.update_id >= self.update_offset: self.update_offset = update.update_id + 1 asyncio.ensure_future(self.process_update(update), loop=self.loop)
def get_stack(self): """ Get the stack for the current Task, or None if there is no Task. """ try: task = Task.current_task() except RuntimeError: # No loop for this thread: task = None if task is None: return None if task not in self._per_task: self._per_task[task] = [] return self._per_task[task]
async def close(self) -> None: """Close the transport""" if self._close_task: await self._close_task return _LOG.info("Close called on discovery service.") self._close_task = Task.current_task(self.loop) if self._transport: self._transport.close() await self._rescan() if self._own_session and self.session: await self.session.close() await asyncio.wait(self._tasks)
async def wrapper(*args, details: EventDetails, **kwargs): current_task = Task.current_task(loop=self._loop) self._request_tasks.add(current_task) async with EventContext(self._parent_context, self._session_details, details) as ctx: try: retval = subscriber.handler(ctx, *args, **kwargs) if isawaitable(retval): await retval except Exception: report_exception( ctx, 'Error running subscription handler for topic {!r}'.format( subscriber.topic), logger=False) raise finally: self._request_tasks.remove(current_task)
async def run(): await sleep(10, loop=loop) print('Connecting...') await driver.connect() print('Wait for login...') await driver.wait_for_login() for contact in await driver.get_unread(): if Task.current_task().cancelled(): break for message in contact.messages: if isinstance(message, Message): # Currently works for text messages only. print('Message from {}: {}'.format(message.sender, message.content)) print('Resending...') contact.chat.chat_send_message(message.safe_content) await sleep(1, loop=loop) await driver.quit()
async def wrapper(*args, _call_details: CallDetails, **kwargs): current_task = Task.current_task(loop=self._loop) self._request_tasks.add(current_task) async with CallContext( self._parent_context, self._session_details, _call_details) as ctx: try: retval = procedure.handler(ctx, *args, **kwargs) if isawaitable(retval): retval = await retval except ApplicationError: raise # These are deliberately raised so no need to report them except Exception as exc: # Report the exception unless it's a mapped exception if exc.__class__ not in self._session._ecls_to_uri_pat: report_exception( ctx, 'Error running handler for procedure {!r}'.format(procedure.name), logger=False) raise finally: self._request_tasks.remove(current_task) return retval
def get_context_or_none(): return getattr(Task.current_task(), 'actor_ctx', None)
def get_context_or_error(): return Task.current_task().actor_ctx