Python tornado.ioloop.IOLoop.current() Examples

The following are 30 code examples of tornado.ioloop.IOLoop.current(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tornado.ioloop.IOLoop , or try the search function .
Example #1
Source File: terminal.py    From TerminalView with MIT License 6 votes vote down vote up
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) 
Example #2
Source File: twisted.py    From tornado-zh with MIT License 6 votes vote down vote up
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 
Example #3
Source File: twisted.py    From tornado-zh with MIT License 6 votes vote down vote up
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 
Example #4
Source File: web.py    From tornado-zh with MIT License 6 votes vote down vote up
def listen(self, port, address="", **kwargs):
        """为应用程序在给定端口上启动一个HTTP server.

        这是一个方便的别名用来创建一个 `.HTTPServer` 对象并调用它
        的listen方法. `HTTPServer.listen <.TCPServer.listen>`
        不支持传递关键字参数给 `.HTTPServer` 构造器. 对于高级用途
        (e.g. 多进程模式), 不要使用这个方法; 创建一个
        `.HTTPServer` 并直接调用它的
        `.TCPServer.bind`/`.TCPServer.start` 方法.

        注意在调用这个方法之后你仍然需要调用
        ``IOLoop.current().start()`` 来启动该服务.

        返回 `.HTTPServer` 对象.

        .. versionchanged:: 4.3
           现在返回 `.HTTPServer` 对象.
        """
        # 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 
Example #5
Source File: web.py    From tornado-zh with MIT License 6 votes vote down vote up
def write_error(self, status_code, **kwargs):
        """复写这个方法来实现自定义错误页.

        ``write_error`` 可能调用 `write`, `render`, `set_header`,等
        来产生一般的输出.

        如果错误是由未捕获的异常造成的(包括HTTPError), 三个一组的
        ``exc_info`` 将变成可用的通过 ``kwargs["exc_info"]``.
        注意这个异常可能不是"当前(current)" 目的或方法的异常就像
        ``sys.exc_info()`` 或 ``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,
                        }) 
Example #6
Source File: chunk_benchmark.py    From tornado-zh with MIT License 6 votes vote down vote up
def main():
    parse_command_line()
    app = Application([('/', ChunkHandler)])
    app.listen(options.port, address='127.0.0.1')

    def callback(response):
        response.rethrow()
        assert len(response.body) == (options.num_chunks * options.chunk_size)
        logging.warning("fetch completed in %s seconds", response.request_time)
        IOLoop.current().stop()

    logging.warning("Starting fetch with curl client")
    curl_client = CurlAsyncHTTPClient()
    curl_client.fetch('http://localhost:%d/' % options.port,
                      callback=callback)
    IOLoop.current().start()

    logging.warning("Starting fetch with simple client")
    simple_client = SimpleAsyncHTTPClient()
    simple_client.fetch('http://localhost:%d/' % options.port,
                        callback=callback)
    IOLoop.current().start() 
Example #7
Source File: twitterdemo.py    From tornado-zh with MIT License 6 votes vote down vote up
def main():
    parse_command_line(final=False)
    parse_config_file(options.config_file)

    app = Application(
        [
            ('/', MainHandler),
            ('/login', LoginHandler),
            ('/logout', LogoutHandler),
        ],
        login_url='/login',
        **options.group_dict('application'))
    app.listen(options.port)

    logging.info('Listening on http://localhost:%d' % options.port)
    IOLoop.current().start() 
Example #8
Source File: gen.py    From tornado-zh with MIT License 6 votes vote down vote up
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 
Example #9
Source File: gen.py    From tornado-zh with MIT License 6 votes vote down vote up
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() 
Example #10
Source File: locks.py    From tornado-zh with MIT License 6 votes vote down vote up
def acquire(self, timeout=None):
        """递减计数器. 返回一个 Future 对象.

        如果计数器(counter)为0将会阻塞, 等待 `.release`. 在超时之后
        Future 对象将会抛出 `.TimeoutError` .
        """
        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 
Example #11
Source File: web.py    From tornado-zh with MIT License 6 votes vote down vote up
def write_error(self, status_code, **kwargs):
        """复写这个方法来实现自定义错误页.

        ``write_error`` 可能调用 `write`, `render`, `set_header`,等
        来产生一般的输出.

        如果错误是由未捕获的异常造成的(包括HTTPError), 三个一组的
        ``exc_info`` 将变成可用的通过 ``kwargs["exc_info"]``.
        注意这个异常可能不是"当前(current)" 目的或方法的异常就像
        ``sys.exc_info()`` 或 ``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,
                        }) 
Example #12
Source File: web.py    From tornado-zh with MIT License 6 votes vote down vote up
def listen(self, port, address="", **kwargs):
        """为应用程序在给定端口上启动一个HTTP server.

        这是一个方便的别名用来创建一个 `.HTTPServer` 对象并调用它
        的listen方法. `HTTPServer.listen <.TCPServer.listen>`
        不支持传递关键字参数给 `.HTTPServer` 构造器. 对于高级用途
        (e.g. 多进程模式), 不要使用这个方法; 创建一个
        `.HTTPServer` 并直接调用它的
        `.TCPServer.bind`/`.TCPServer.start` 方法.

        注意在调用这个方法之后你仍然需要调用
        ``IOLoop.current().start()`` 来启动该服务.

        返回 `.HTTPServer` 对象.

        .. versionchanged:: 4.3
           现在返回 `.HTTPServer` 对象.
        """
        # 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 
Example #13
Source File: twisted.py    From tornado-zh with MIT License 6 votes vote down vote up
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 
Example #14
Source File: twisted.py    From tornado-zh with MIT License 6 votes vote down vote up
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 
Example #15
Source File: gen.py    From tornado-zh with MIT License 6 votes vote down vote up
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 
Example #16
Source File: gen.py    From tornado-zh with MIT License 6 votes vote down vote up
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() 
Example #17
Source File: locks.py    From tornado-zh with MIT License 6 votes vote down vote up
def acquire(self, timeout=None):
        """递减计数器. 返回一个 Future 对象.

        如果计数器(counter)为0将会阻塞, 等待 `.release`. 在超时之后
        Future 对象将会抛出 `.TimeoutError` .
        """
        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 
Example #18
Source File: terminal.py    From TerminalView with MIT License 6 votes vote down vote up
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 
Example #19
Source File: terminal.py    From TerminalView with MIT License 6 votes vote down vote up
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 
Example #20
Source File: terminal.py    From TerminalView with MIT License 6 votes vote down vote up
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 
Example #21
Source File: gen.py    From tornado-zh with MIT License 5 votes vote down vote up
def _return_result(self, done):
        """Called set the returned future's state that of the future
        we yielded, and set the current future for the iterator.
        """
        chain_future(done, self._running_future)

        self.current_future = done
        self.current_index = self._unfinished.pop(done) 
Example #22
Source File: caresresolver.py    From tornado-zh with MIT License 5 votes vote down vote up
def initialize(self, io_loop=None):
        self.io_loop = io_loop or IOLoop.current()
        self.channel = pycares.Channel(sock_state_cb=self._sock_state_cb)
        self.fds = {} 
Example #23
Source File: gen_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def prepare(self):
        self.chunks = []
        yield gen.Task(IOLoop.current().add_callback)
        self.chunks.append('1') 
Example #24
Source File: gen.py    From tornado-zh with MIT License 5 votes vote down vote up
def _return_result(self, done):
        """Called set the returned future's state that of the future
        we yielded, and set the current future for the iterator.
        """
        chain_future(done, self._running_future)

        self.current_future = done
        self.current_index = self._unfinished.pop(done) 
Example #25
Source File: gen_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def get(self):
        self.chunks.append('2')
        yield gen.Task(IOLoop.current().add_callback)
        self.chunks.append('3')
        yield gen.Task(IOLoop.current().add_callback)
        self.write(''.join(self.chunks)) 
Example #26
Source File: gen_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def prepare(self):
        yield gen.Task(IOLoop.current().add_callback)
        raise HTTPError(403) 
Example #27
Source File: gen_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_empty_iterator(self):
        g = gen.WaitIterator()
        self.assertTrue(g.done(), 'empty generator iterated')

        with self.assertRaises(ValueError):
            g = gen.WaitIterator(False, bar=False)

        self.assertEqual(g.current_index, None, "bad nil current index")
        self.assertEqual(g.current_future, None, "bad nil current future") 
Example #28
Source File: simple_httpclient_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def async_body_producer(self, write):
        yield write(b'1234')
        yield gen.Task(IOLoop.current().add_callback)
        yield write(b'5678') 
Example #29
Source File: gen.py    From tornado-zh with MIT License 5 votes vote down vote up
def done(self):
        """Returns True if this iterator has no more results."""
        if self._finished or self._unfinished:
            return False
        # Clear the 'current' values when iteration is done.
        self.current_index = self.current_future = None
        return True 
Example #30
Source File: simple_httpclient_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_native_body_producer_chunked(self):
        namespace = exec_test(globals(), locals(), """
        async def body_producer(write):
            await write(b'1234')
            await gen.Task(IOLoop.current().add_callback)
            await write(b'5678')
        """)
        response = self.fetch("/echo_post", method="POST",
                              body_producer=namespace["body_producer"])
        response.rethrow()
        self.assertEqual(response.body, b"12345678")