Python tornado.httpserver() Examples

The following are 20 code examples of tornado.httpserver(). 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 , or try the search function .
Example #1
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 #2
Source File: web.py    From EventGhost with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #3
Source File: init.py    From RobotAIEngine with Apache License 2.0 6 votes vote down vote up
def main():
    ''' main 函数
    '''
    # 开启 search_engin_server
    ioloop = tornado.ioloop.IOLoop.instance()
    server = tornado.httpserver.HTTPServer(Application(), xheaders=True)
    server.listen(options.port)

    def sig_handler(sig, _):
        ''' 信号接收函数
        '''
        logging.warn("Caught signal: %s", sig)
        shutdown(ioloop, server)

    signal.signal(signal.SIGTERM, sig_handler)
    signal.signal(signal.SIGINT, sig_handler)
    ioloop.start() 
Example #4
Source File: init.py    From RobotAIEngine with Apache License 2.0 6 votes vote down vote up
def shutdown(ioloop, server):
    ''' 关闭server

    :param server: tornado.httpserver.HTTPServer
    '''
    logging.info(
        "HTTP interpreter service will shutdown in %ss...", 1)
    server.stop()

    deadline = time.time() + 1

    def stop_loop():
        ''' 尝试关闭loop
        '''
        now = time.time()
        if now < deadline and (ioloop._callbacks or ioloop._timeouts):
            ioloop.add_timeout(now + 1, stop_loop)
        else:
            # 处理完现有的 callback 和 timeout 后
            ioloop.stop()
            logging.info('Shutdown!')

    stop_loop() 
Example #5
Source File: plugin.py    From pytest-tornado with Apache License 2.0 6 votes vote down vote up
def https_server(request, io_loop, _unused_port):
    """Start a tornado HTTPS server.

    You must create an `app` fixture, which returns
    the `tornado.web.Application` to be tested.

    Raises:
        FixtureLookupError: tornado application fixture not found
    """
    https_app = request.getfixturevalue(request.config.option.app_fixture)
    ssl_options = request.getfixturevalue(request.config.option.ssl_options_fixture)
    server = tornado.httpserver.HTTPServer(https_app, ssl_options=ssl_options)
    server.add_socket(_unused_port[0])

    def _stop():
        server.stop()

        if hasattr(server, 'close_all_connections'):
            io_loop.run_sync(server.close_all_connections,
                             timeout=request.config.option.async_test_timeout)

    request.addfinalizer(_stop)
    return server 
Example #6
Source File: plugin.py    From pytest-tornado with Apache License 2.0 6 votes vote down vote up
def http_server(request, io_loop, _unused_port):
    """Start a tornado HTTP server.

    You must create an `app` fixture, which returns
    the `tornado.web.Application` to be tested.

    Raises:
        FixtureLookupError: tornado application fixture not found
    """
    http_app = request.getfixturevalue(request.config.option.app_fixture)
    server = tornado.httpserver.HTTPServer(http_app)
    server.add_socket(_unused_port[0])

    def _stop():
        server.stop()

        if hasattr(server, 'close_all_connections'):
            io_loop.run_sync(server.close_all_connections,
                             timeout=request.config.option.async_test_timeout)

    request.addfinalizer(_stop)
    return server 
Example #7
Source File: web.py    From honeything with GNU General Public License v3.0 6 votes vote down vote up
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 are passed to the HTTPServer
        constructor.  For advanced uses (e.g. preforking), do not use
        this method; create an HTTPServer and call its bind/start
        methods directly.

        Note that after calling this method you still need to call
        IOLoop.instance().start() to start the server.
        """
        # 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) 
Example #8
Source File: web.py    From pySINDy with MIT License 6 votes vote down vote up
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 
Example #9
Source File: web.py    From teleport with Apache License 2.0 6 votes vote down vote up
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 
Example #10
Source File: web.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
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.instance().start()`` to start the server.
        """
        # 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) 
Example #11
Source File: web.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
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.instance().start()`` to start the server.
        """
        # 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) 
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: web.py    From viewfinder with Apache License 2.0 5 votes vote down vote up
def cookies(self):
        """An alias for `self.request.cookies <.httpserver.HTTPRequest.cookies>`."""
        return self.request.cookies 
Example #14
Source File: webutils.py    From treadmill with Apache License 2.0 5 votes vote down vote up
def run_wsgi(wsgi_app, port):
    """Runs wsgi (Flask) app using tornado web server."""

    container = tornado.wsgi.WSGIContainer(wsgi_app)
    app = tornado.web.Application([
        (r'.*', tornado.web.FallbackHandler, dict(fallback=container)),
    ])

    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(port)
    tornado.ioloop.IOLoop.instance().start() 
Example #15
Source File: webutils.py    From treadmill with Apache License 2.0 5 votes vote down vote up
def run_wsgi_unix(wsgi_app, socket):
    """Runs wsgi (Flask) app using tornado unixsocket web server."""

    container = tornado.wsgi.WSGIContainer(wsgi_app)
    app = tornado.web.Application([
        (r'.*', tornado.web.FallbackHandler, dict(fallback=container)),
    ])

    http_server = tornado.httpserver.HTTPServer(app)
    unix_socket = tornado.netutil.bind_unix_socket(socket)
    http_server.add_socket(unix_socket)
    tornado.ioloop.IOLoop.instance().start() 
Example #16
Source File: web.py    From viewfinder with Apache License 2.0 5 votes vote down vote up
def cookies(self):
        """An alias for `self.request.cookies <.httpserver.HTTPRequest.cookies>`."""
        return self.request.cookies 
Example #17
Source File: helloworld.py    From honeything with GNU General Public License v3.0 4 votes vote down vote up
def main():
    tornado.options.parse_command_line()
    application = tornado.web.Application([
        (r"/", MainHandler),
    ])
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start() 
Example #18
Source File: _background_server.py    From colabtools with Apache License 2.0 4 votes vote down vote up
def start(self, port=None, timeout=1):
    """Starts a server in a thread using the WSGI application provided.

    Will wait until the thread has started calling with an already serving
    application will simple return.

    Args:
      port: Number of the port to use for the application, will find an open
        port if a nonzero port is not provided.
      timeout: Http timeout in seconds. Note that this is only respected under
        tornado v4.

    Raises:
      RuntimeError: if server is already started.
    """
    if self._server_thread is not None:
      raise RuntimeError('start() called on running background server.')

    self._port = port or portpicker.pick_unused_port()

    # Support both internal & external colab (tornado v3 vs. v4)
    # TODO(b/35548011): remove tornado v3 handling
    if tornado.version[0] >= '4':
      kwds = {'idle_connection_timeout': timeout, 'body_timeout': timeout}
    else:
      kwds = {}
    self._server = tornado.httpserver.HTTPServer(self._app, **kwds)
    self._ioloop = tornado.ioloop.IOLoop()

    def start_server(httpd, ioloop, port):
      # TODO(b/147233568): Restrict this to local connections.
      host = ''  # Bind to all
      ioloop.make_current()
      httpd.listen(port=port, address=host)
      ioloop.start()

    self._server_thread = threading.Thread(
        target=start_server,
        kwargs={
            'httpd': self._server,
            'ioloop': self._ioloop,
            'port': self._port
        })
    started = threading.Event()
    self._ioloop.add_callback(started.set)
    self._server_thread.start()
    started.wait() 
Example #19
Source File: gtornado.py    From Flask-P2P with MIT License 4 votes vote down vote up
def run(self):
        self.ioloop = IOLoop.instance()
        self.alive = True
        PeriodicCallback(self.watchdog, 1000, io_loop=self.ioloop).start()

        # Assume the app is a WSGI callable if its not an
        # instance of tornado.web.Application or is an
        # instance of tornado.wsgi.WSGIApplication
        app = self.wsgi
        if not isinstance(app, tornado.web.Application) or \
           isinstance(app, tornado.wsgi.WSGIApplication):
            app = WSGIContainer(app)

        # Monkey-patching HTTPConnection.finish to count the
        # number of requests being handled by Tornado. This
        # will help gunicorn shutdown the worker if max_requests
        # is exceeded.
        httpserver = sys.modules["tornado.httpserver"]
        if hasattr(httpserver, 'HTTPConnection'):
            old_connection_finish = httpserver.HTTPConnection.finish

            def finish(other):
                self.handle_request()
                old_connection_finish(other)
            httpserver.HTTPConnection.finish = finish
            sys.modules["tornado.httpserver"] = httpserver

            server_class = tornado.httpserver.HTTPServer
        else:

            class _HTTPServer(tornado.httpserver.HTTPServer):

                def on_close(instance, server_conn):
                    self.handle_request()
                    super(_HTTPServer, instance).on_close(server_conn)

            server_class = _HTTPServer

        if self.cfg.is_ssl:
            server = server_class(app, io_loop=self.ioloop,
                    ssl_options=self.cfg.ssl_options)
        else:
            server = server_class(app, io_loop=self.ioloop)

        self.server = server

        for s in self.sockets:
            s.setblocking(0)
            if hasattr(server, "add_socket"):  # tornado > 2.0
                server.add_socket(s)
            elif hasattr(server, "_sockets"):  # tornado 2.0
                server._sockets[s.fileno()] = s

        server.no_keep_alive = self.cfg.keepalive <= 0
        server.start(num_processes=1)

        self.ioloop.start() 
Example #20
Source File: app.py    From webspider with MIT License 4 votes vote down vote up
def main():
    define(name='port', default=8000, type=int, help='run on the given port')
    parse_command_line()
    logger.info('====== web server starting at http://0.0.0.0:{} ======'.format(options.port))
    if constants.DEBUG:
        logger.info('debug mode is enabled!!!')

    app = make_web_app()
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    http_server.start()

    tornado.ioloop.IOLoop.instance().start()