我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用tornado.ioloop.IOLoop.current()。
def create_attribute(self, cls, attr_name): async_method = self.property.create_attribute(cls, attr_name) original_class = self.original_class @functools.wraps(async_method) @motor_coroutine def wrapper(self, *args, **kwargs): result = yield async_method(self, *args, **kwargs) # Don't call isinstance(), not checking subclasses. if result.__class__ == original_class: # Delegate to the current object to wrap the result. raise gen.Return(self.wrap(result)) else: raise gen.Return(result) if self.doc: wrapper.__doc__ = self.doc return wrapper
def test_and_set(self, key, value, prev_value, ttl=None, callback=None): """ Atomic test & set operation. It will check if the value of 'key' is 'prev_value', if the the check is correct will change the value for 'key' to 'value' if the the check is false an exception will be raised. Args: key (str): Key. value (object): value to set prev_value (object): previous value. ttl (int): Time in seconds of expiration (optional). Returns: client.EtcdResult Raises: ValueError: When the 'prev_value' is not the current value. >>> print client.test_and_set('/key', 'new', 'old', ttl=60).value 'new' """ return self.write(key, value, prevValue=prev_value, ttl=ttl, callback=callback)
def save_cursor_position(self, mode=None): """ Saves the cursor position and current rendition settings to :attr:`self.saved_cursorX`, :attr:`self.saved_cursorY`, and :attr:`self.saved_rendition` .. note:: Also handles the set/restore "Private Mode Settings" sequence. """ if mode: # Set DEC private mode # TODO: Need some logic here to save the current expanded mode # so we can restore it in _set_top_bottom(). self.set_expanded_mode(mode) # NOTE: args and kwargs are here to make sure we don't get an exception # when we're called via escape sequences. self.saved_cursorX = self.cursorX self.saved_cursorY = self.cursorY self.saved_rendition = self.cur_rendition
def _dsr_get_cursor_position(self): """ Returns the current cursor positition as a DSR response in the form of:: '\x1b<self.cursorY>;<self.cursorX>R' Also executes CALLBACK_DSR with the same output as the first argument. Example:: self.callbacks[CALLBACK_DSR]('\x1b20;123R') """ esc_cursor_pos = '\x1b%s;%sR' % (self.cursorY, self.cursorX) try: for callback in self.callbacks[CALLBACK_DSR].values(): callback(esc_cursor_pos) except TypeError: pass return esc_cursor_pos
def insert_line(self, n=1): """ Inserts *n* lines at the current cursor position. """ #logging.debug("insert_line(%s)" % n) if not n: # Takes care of an empty string n = 1 n = int(n) for i in xrange(n): self.screen.pop(self.bottom_margin) # Remove the bottom line # Remove bottom line's style information as well: self.renditions.pop(self.bottom_margin) empty_line = array('u', u' ' * self.cols) # Line full of spaces self.screen.insert(self.cursorY, empty_line) # Insert at cursor # Insert a new empty rendition as well: empty_rend = array('u', unichr(1000) * self.cols) self.renditions.insert(self.cursorY, empty_rend) # Insert at cursor
def delete_line(self, n=1): """ Deletes *n* lines at the current cursor position. """ #logging.debug("delete_line(%s)" % n) if not n: # Takes care of an empty string n = 1 n = int(n) for i in xrange(n): self.screen.pop(self.cursorY) # Remove the line at the cursor # Remove the line's style information as well: self.renditions.pop(self.cursorY) # Now add an empty line and empty set of renditions to the bottom of # the view empty_line = array('u', u' ' * self.cols) # Line full of spaces # Add it to the bottom of the view: self.screen.insert(self.bottom_margin, empty_line) # Insert at bottom # Insert a new empty rendition as well: empty_rend = array('u', unichr(1000) * self.cols) self.renditions.insert(self.bottom_margin, empty_rend)
def _filetype_instance(self): """ Instantiates a new instance of the given :class:`FileType` (using `self.matched_header`) and stores the result in `self.captured_files` and creates a reference to that location at the current cursor location. """ ref = self.file_counter.next() logging.debug("_filetype_instance(%s)" % repr(ref)) # Before doing anything else we need to mark the current cursor # location as belonging to our file self.screen[self.cursorY][self.cursorX] = ref # Create an instance of the filetype we can reference filetype_instance = self.magic_map[self.matched_header]( path=self.temppath, linkpath=self.linkpath, icondir=self.icondir) self.captured_files[ref] = filetype_instance
def dump_components(self): """ Dumps the screen and renditions as-is, the scrollback buffer as HTML, and the current cursor coordinates. Also, empties the scrollback buffer .. note:: This was used in some performance-related experiments but might be useful for other patterns in the future so I've left it here. """ screen = [a.tounicode() for a in self.screen] scrollback = [] if self.scrollback_buf: # Process the scrollback buffer into HTML scrollback = self._spanify_scrollback( self.scrollback_buf, self.scrollback_renditions) # Empty the scrollback buffer: self.init_scrollback() self.modified = False return (scrollback, screen, self.renditions, self.cursorY, self.cursorX)
def __init__(self, *args, **kwargs): """Create a new connection to a single MongoDB instance at *host:port*. MotorClient takes the same constructor arguments as :class:`~pymongo.mongo_client.MongoClient`, as well as: :Parameters: - `io_loop` (optional): Special :class:`tornado.ioloop.IOLoop` instance to use instead of default """ if 'io_loop' in kwargs: io_loop = kwargs.pop('io_loop') else: io_loop = ioloop.IOLoop.current() event_class = functools.partial(util.MotorGreenletEvent, io_loop) kwargs['_event_class'] = event_class super(MotorClient, self).__init__(io_loop, *args, **kwargs)
def __init__(self, *args, **kwargs): """Create a new connection to a MongoDB replica set. MotorReplicaSetClient takes the same constructor arguments as :class:`~pymongo.mongo_replica_set_client.MongoReplicaSetClient`, as well as: :Parameters: - `io_loop` (optional): Special :class:`tornado.ioloop.IOLoop` instance to use instead of default """ if 'io_loop' in kwargs: io_loop = kwargs.pop('io_loop') else: io_loop = ioloop.IOLoop.current() kwargs['_monitor_class'] = functools.partial( MotorReplicaSetMonitor, io_loop) super(MotorReplicaSetClient, self).__init__(io_loop, *args, **kwargs)
def __del__(self): # This MotorCursor is deleted on whatever greenlet does the last # decref, or (if it's referenced from a cycle) whichever is current # when the GC kicks in. We may need to send the server a killCursors # message, but in Motor only direct children of the main greenlet can # do I/O. First, do a quick check whether the cursor is still alive on # the server: if self.cursor_id and self.alive: if greenlet.getcurrent().parent is not None: # We're on a child greenlet, send the message. self.delegate.close() else: # We're on the main greenlet, start the operation on a child. self.close() # Paper over some differences between PyMongo Cursor and CommandCursor.
def __new__(cls, io_loop=None, force_instance=False, **kwargs): io_loop = io_loop or IOLoop.current() if force_instance: instance_cache = None else: instance_cache = cls._async_clients() if instance_cache is not None and io_loop in instance_cache: return instance_cache[io_loop] instance = super(AsyncHTTPClient, cls).__new__(cls, io_loop=io_loop, **kwargs) # Make sure the instance knows which cache to remove itself from. # It can't simply call _async_clients() because we may be in # __new__(AsyncHTTPClient) but instance.__class__ may be # SimpleAsyncHTTPClient. instance._instance_cache = instance_cache if instance_cache is not None: instance_cache[instance.io_loop] = instance return instance
def wait(self, timeout=None): """Wait for `.notify`. Returns a `.Future` that resolves ``True`` if the condition is notified, or ``False`` after a timeout. """ waiter = Future() self._waiters.append(waiter) if timeout: def on_timeout(): waiter.set_result(False) self._garbage_collect() io_loop = ioloop.IOLoop.current() timeout_handle = io_loop.add_timeout(timeout, on_timeout) waiter.add_done_callback( lambda _: io_loop.remove_timeout(timeout_handle)) return waiter
def acquire(self, timeout=None): """Decrement the counter. Returns a Future. Block if the counter is zero and wait for a `.release`. The Future raises `.TimeoutError` after the deadline. """ waiter = Future() if self._value > 0: self._value -= 1 waiter.set_result(_ReleasingContextManager(self)) else: self._waiters.append(waiter) if timeout: def on_timeout(): waiter.set_exception(gen.TimeoutError()) self._garbage_collect() io_loop = ioloop.IOLoop.current() timeout_handle = io_loop.add_timeout(timeout, on_timeout) waiter.add_done_callback( lambda _: io_loop.remove_timeout(timeout_handle)) return waiter
def add_sockets(self, sockets): """Makes this server start accepting connections on the given sockets. The ``sockets`` parameter is a list of socket objects such as those returned by `~tornado.netutil.bind_sockets`. `add_sockets` is typically used in combination with that method and `tornado.process.fork_processes` to provide greater control over the initialization of a multi-process server. """ if self.io_loop is None: self.io_loop = IOLoop.current() for sock in sockets: self._sockets[sock.fileno()] = sock add_accept_handler(sock, self._handle_connection, io_loop=self.io_loop)
def __init__(self, io_loop=None): if not io_loop: io_loop = tornado.ioloop.IOLoop.current() self._io_loop = io_loop self._readers = {} # map of reader objects to fd self._writers = {} # map of writer objects to fd self._fds = {} # a map of fd to a (reader, writer) tuple self._delayedCalls = {} PosixReactorBase.__init__(self) self.addSystemEventTrigger('during', 'shutdown', self.crash) # IOLoop.start() bypasses some of the reactor initialization. # Fire off the necessary events if they weren't already triggered # by reactor.run(). def start_if_necessary(): if not self._started: self.fireSystemEvent('startup') self._io_loop.add_callback(start_if_necessary) # IReactorTime
def install(io_loop=None): """Install this package as the default Twisted reactor. ``install()`` must be called very early in the startup process, before most other twisted-related imports. Conversely, because it initializes the `.IOLoop`, it cannot be called before `.fork_processes` or multi-process `~.TCPServer.start`. These conflicting requirements make it difficult to use `.TornadoReactor` in multi-process mode, and an external process manager such as ``supervisord`` is recommended instead. .. versionchanged:: 4.1 The ``io_loop`` argument is deprecated. """ if not io_loop: io_loop = tornado.ioloop.IOLoop.current() reactor = TornadoReactor(io_loop) from twisted.internet.main import installReactor installReactor(reactor) return reactor
def sleep(duration): """Return a `.Future` that resolves after the given number of seconds. When used with ``yield`` in a coroutine, this is a non-blocking analogue to `time.sleep` (which should not be used in coroutines because it is blocking):: yield gen.sleep(0.5) Note that calling this function on its own does nothing; you must wait on the `.Future` it returns (usually by yielding it). .. versionadded:: 4.1 """ f = Future() IOLoop.current().call_later(duration, lambda: f.set_result(None)) return f
def __init__(self, gen, result_future, first_yielded): self.gen = gen self.result_future = result_future self.future = _null_future self.yield_point = None self.pending_callbacks = None self.results = None self.running = False self.finished = False self.had_exception = False self.io_loop = IOLoop.current() # For efficiency, we do not create a stack context until we # reach a YieldPoint (stack contexts are required for the historical # semantics of YieldPoints, but not for Futures). When we have # done so, this field will be set and must be called at the end # of the coroutine. self.stack_context_deactivate = None if self.handle_yield(first_yielded): self.run()
def write_error(self, status_code, **kwargs): """Override to implement custom error pages. ``write_error`` may call `write`, `render`, `set_header`, etc to produce output as usual. If this error was caused by an uncaught exception (including HTTPError), an ``exc_info`` triple will be available as ``kwargs["exc_info"]``. Note that this exception may not be the "current" exception for purposes of methods like ``sys.exc_info()`` or ``traceback.format_exc``. """ if self.settings.get("serve_traceback") and "exc_info" in kwargs: # in debug mode, try to send a traceback self.set_header('Content-Type', 'text/plain') for line in traceback.format_exception(*kwargs["exc_info"]): self.write(line) self.finish() else: self.finish("<html><title>%(code)d: %(message)s</title>" "<body>%(code)d: %(message)s</body></html>" % { "code": status_code, "message": self._reason, })
def locale(self): """The locale for the current session. Determined by either `get_user_locale`, which you can override to set the locale based on, e.g., a user preference stored in a database, or `get_browser_locale`, which uses the ``Accept-Language`` header. .. versionchanged: 4.1 Added a property setter. """ if not hasattr(self, "_locale"): self._locale = self.get_user_locale() if not self._locale: self._locale = self.get_browser_locale() assert self._locale return self._locale
def listen(self, port, address="", **kwargs): """Starts an HTTP server for this application on the given port. This is a convenience alias for creating an `.HTTPServer` object and calling its listen method. Keyword arguments not supported by `HTTPServer.listen <.TCPServer.listen>` are passed to the `.HTTPServer` constructor. For advanced uses (e.g. multi-process mode), do not use this method; create an `.HTTPServer` and call its `.TCPServer.bind`/`.TCPServer.start` methods directly. Note that after calling this method you still need to call ``IOLoop.current().start()`` to start the server. Returns the `.HTTPServer` object. .. versionchanged:: 4.3 Now returns the `.HTTPServer` object. """ # import is here rather than top level because HTTPServer # is not importable on appengine from tornado.httpserver import HTTPServer server = HTTPServer(self, **kwargs) server.listen(port, address) return server