Python tornado.httpserver.HTTPServer() Examples

The following are 30 code examples of tornado.httpserver.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.httpserver , or try the search function .
Example #1
Source File: httpclient_test.py    From opendevops with GNU General Public License v3.0 6 votes vote down vote up
def setUp(self):
        self.server_ioloop = IOLoop()
        event = threading.Event()

        @gen.coroutine
        def init_server():
            sock, self.port = bind_unused_port()
            app = Application([("/", HelloWorldHandler)])
            self.server = HTTPServer(app)
            self.server.add_socket(sock)
            event.set()

        def start():
            self.server_ioloop.run_sync(init_server)
            self.server_ioloop.start()

        self.server_thread = threading.Thread(target=start)
        self.server_thread.start()
        event.wait()

        self.http_client = HTTPClient() 
Example #2
Source File: httpserver_test.py    From tornado-zh with MIT License 6 votes vote down vote up
def test_missing_key(self):
        """A missing SSL key should cause an immediate exception."""

        application = Application()
        module_dir = os.path.dirname(__file__)
        existing_certificate = os.path.join(module_dir, 'test.crt')
        existing_key = os.path.join(module_dir, 'test.key')

        self.assertRaises((ValueError, IOError),
                          HTTPServer, application, ssl_options={
                              "certfile": "/__mising__.crt",
        })
        self.assertRaises((ValueError, IOError),
                          HTTPServer, application, ssl_options={
                              "certfile": existing_certificate,
                              "keyfile": "/__missing__.key"
        })

        # This actually works because both files exist
        HTTPServer(application, ssl_options={
                   "certfile": existing_certificate,
                   "keyfile": existing_key,
                   }) 
Example #3
Source File: httpserver_test.py    From tornado-zh with MIT License 6 votes vote down vote up
def test_chunked_request_body(self):
        # Chunked requests are not widely supported and we don't have a way
        # to generate them in AsyncHTTPClient, but HTTPServer will read them.
        self.stream.write(b"""\
POST /echo HTTP/1.1
Transfer-Encoding: chunked
Content-Type: application/x-www-form-urlencoded

4
foo=
3
bar
0

""".replace(b"\n", b"\r\n"))
        read_stream_body(self.stream, self.stop)
        headers, response = self.wait()
        self.assertEqual(json_decode(response), {u('foo'): [u('bar')]}) 
Example #4
Source File: app.py    From binderhub with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def start(self, run_loop=True):
        self.log.info("BinderHub starting on port %i", self.port)
        self.http_server = HTTPServer(
            self.tornado_app,
            xheaders=True,
        )
        self.http_server.listen(self.port)
        if self.builder_required:
            asyncio.ensure_future(self.watch_build_pods())
        if run_loop:
            tornado.ioloop.IOLoop.current().start() 
Example #5
Source File: httpclient_test.py    From tornado-zh with MIT License 6 votes vote down vote up
def setUp(self):
        if IOLoop.configured_class().__name__ in ('TwistedIOLoop',
                                                  'AsyncIOMainLoop'):
            # TwistedIOLoop only supports the global reactor, so we can't have
            # separate IOLoops for client and server threads.
            # AsyncIOMainLoop doesn't work with the default policy
            # (although it could with some tweaks to this test and a
            # policy that created loops for non-main threads).
            raise unittest.SkipTest(
                'Sync HTTPClient not compatible with TwistedIOLoop or '
                'AsyncIOMainLoop')
        self.server_ioloop = IOLoop()

        sock, self.port = bind_unused_port()
        app = Application([('/', HelloWorldHandler)])
        self.server = HTTPServer(app, io_loop=self.server_ioloop)
        self.server.add_socket(sock)

        self.server_thread = threading.Thread(target=self.server_ioloop.start)
        self.server_thread.start()

        self.http_client = HTTPClient() 
Example #6
Source File: httpserver_test.py    From tornado-zh with MIT License 6 votes vote down vote up
def test_chunked_request_body(self):
        # Chunked requests are not widely supported and we don't have a way
        # to generate them in AsyncHTTPClient, but HTTPServer will read them.
        self.stream.write(b"""\
POST /echo HTTP/1.1
Transfer-Encoding: chunked
Content-Type: application/x-www-form-urlencoded

4
foo=
3
bar
0

""".replace(b"\n", b"\r\n"))
        read_stream_body(self.stream, self.stop)
        headers, response = self.wait()
        self.assertEqual(json_decode(response), {u('foo'): [u('bar')]}) 
Example #7
Source File: __main__.py    From ATX with Apache License 2.0 6 votes vote down vote up
def cmd_web(unix_socket, debug):
    app = make_app(debug=debug)
    server = HTTPServer(app)
    if os.path.exists(unix_socket):
        try:
            r = requests.get('http+unix://{0}'.format(unix_socket.replace('/', '%2F')))
            if r.text.strip() == 'atx.taskqueue':
                print 'Already listening'
                return
        except:
            print 'Unlink unix socket'
            os.unlink(unix_socket)

    socket = bind_unix_socket(unix_socket)
    server.add_socket(socket)
    IOLoop.current().start() 
Example #8
Source File: snap.py    From pypot with GNU General Public License v3.0 6 votes vote down vote up
def run(self, quiet=None, server=''):
        """ Start the tornado server, run forever.
            'quiet' and 'server' arguments are no longer used, they are keep only for backward compatibility
        """

        try:
            loop = IOLoop()
            http_server = HTTPServer(WSGIContainer(self.app))
            http_server.listen(self.port)
            loop.start()

        except socket.error as serr:
            # Re raise the socket error if not "[Errno 98] Address already in use"
            if serr.errno != errno.EADDRINUSE:
                raise serr
            else:
                logger.warning("""The webserver port {} is already used.
The SnapRobotServer is maybe already run or another software use this port.""".format(self.port)) 
Example #9
Source File: benchmark.py    From tornado_http2 with Apache License 2.0 6 votes vote down vote up
def benchmark(version):
    app = Application([('/', HelloHandler)])
    if version == 1:
        server = HTTPServer(app)
        client = AsyncHTTPClient()
    elif version == 2:
        server = tornado_http2.server.CleartextHTTP2Server(app)
        client = tornado_http2.client.ForceHTTP2Client()

    sock, port = bind_unused_port()
    try:
        server.add_socket(sock)
        url = 'http://localhost:%d/' % port

        start = time.time()
        for i in range(options.n):
            yield client.fetch(url)
        end = time.time()
        return end - start
    finally:
        server.stop()
        sock.close() 
Example #10
Source File: __init__.py    From ServerMsgPush with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def main():
    global config, output_wechat, app
    config = ConfigParser()
    config.read('config')
    from .utility import output_wechat
    app = Application()

    parse_command_line()
    try:
        from .views import app
        http_server = HTTPServer(app)
        http_server.listen(config['base']['port'])
        IOLoop.current().start()
    except Exception as e:
        print(e)
    finally:
        with open('config', 'w') as f:
            config.write(f) 
Example #11
Source File: httpserver_test.py    From opendevops with GNU General Public License v3.0 6 votes vote down vote up
def test_chunked_request_body(self):
        # Chunked requests are not widely supported and we don't have a way
        # to generate them in AsyncHTTPClient, but HTTPServer will read them.
        self.stream.write(
            b"""\
POST /echo HTTP/1.1
Transfer-Encoding: chunked
Content-Type: application/x-www-form-urlencoded

4
foo=
3
bar
0

""".replace(
                b"\n", b"\r\n"
            )
        )
        start_line, headers, response = self.io_loop.run_sync(
            lambda: read_stream_body(self.stream)
        )
        self.assertEqual(json_decode(response), {u"foo": [u"bar"]}) 
Example #12
Source File: httpserver_test.py    From pySINDy with MIT License 6 votes vote down vote up
def test_missing_key(self):
        """A missing SSL key should cause an immediate exception."""

        application = Application()
        module_dir = os.path.dirname(__file__)
        existing_certificate = os.path.join(module_dir, 'test.crt')
        existing_key = os.path.join(module_dir, 'test.key')

        self.assertRaises((ValueError, IOError),
                          HTTPServer, application, ssl_options={
                              "certfile": "/__mising__.crt",
        })
        self.assertRaises((ValueError, IOError),
                          HTTPServer, application, ssl_options={
                              "certfile": existing_certificate,
                              "keyfile": "/__missing__.key"
        })

        # This actually works because both files exist
        HTTPServer(application, ssl_options={
                   "certfile": existing_certificate,
                   "keyfile": existing_key,
                   }) 
Example #13
Source File: webserver.py    From torngas with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _patch_httpserver(self):
        """
        重写httpserver的xheader配置,让gunicorn可以加载xheaders设置
        :return:
        """
        httpserver = sys.modules["tornado.httpserver"]
        try:
            xhs = settings.XHEADERS
        except:
            xhs = True

        class TorngasHTTPServer(httpserver.HTTPServer):
            def __init__(self, request_callback, xheaders=xhs, **kwargs):
                super(TorngasHTTPServer, self).__init__(request_callback,
                                                        xheaders=xheaders,
                                                        **kwargs)

        httpserver.HTTPServer = TorngasHTTPServer
        sys.modules["tornado.httpserver"] = httpserver 
Example #14
Source File: webserver.py    From torngas with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def load_httpserver(self, sockets=None, **kwargs):
        if not sockets:
            from tornado.netutil import bind_sockets

            if settings.IPV4_ONLY:
                import socket

                sockets = bind_sockets(options.port, options.address, family=socket.AF_INET)
            else:
                sockets = bind_sockets(options.port, options.address)

        http_server = tornado.httpserver.HTTPServer(self.application, **kwargs)

        http_server.add_sockets(sockets)
        self.httpserver = http_server
        return self.httpserver 
Example #15
Source File: bast.py    From Bast with MIT License 6 votes vote down vote up
def run(self):
        """
        Function to Run the server. Server runs on host: 127.0.0.1 and port: 2000 by default. Debug is also set to false
        by default

        Can be overriden by using the config.ini file
        """
        define("port", default=self.port, help="Run on given port", type=int)
        define("host", default=self.host, help="Run on given host", type=str)
        define("debug", default=self.debug, help="True for development", type=bool)

        parse_command_line()

        print(Fore.GREEN + "Starting Bast Server....")
        print(Fore.GREEN + "Bast Server Running on %s:%s" % (options.host, options.port))

        application = Application(self.handler, debug=options.debug)
        server = HTTPServer(application)
        server.listen(options.port, options.host)
        IOLoop.current().start() 
Example #16
Source File: httpclient_test.py    From pySINDy with MIT License 6 votes vote down vote up
def setUp(self):
        if IOLoop.configured_class().__name__ == 'TwistedIOLoop':
            # TwistedIOLoop only supports the global reactor, so we can't have
            # separate IOLoops for client and server threads.
            raise unittest.SkipTest(
                'Sync HTTPClient not compatible with TwistedIOLoop')
        self.server_ioloop = IOLoop()

        @gen.coroutine
        def init_server():
            sock, self.port = bind_unused_port()
            app = Application([('/', HelloWorldHandler)])
            self.server = HTTPServer(app)
            self.server.add_socket(sock)
        self.server_ioloop.run_sync(init_server)

        self.server_thread = threading.Thread(target=self.server_ioloop.start)
        self.server_thread.start()

        self.http_client = HTTPClient() 
Example #17
Source File: httpclient_test.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        if IOLoop.configured_class().__name__ == 'TwistedIOLoop':
            # TwistedIOLoop only supports the global reactor, so we can't have
            # separate IOLoops for client and server threads.
            raise unittest.SkipTest(
                'Sync HTTPClient not compatible with TwistedIOLoop')
        self.server_ioloop = IOLoop()

        sock, self.port = bind_unused_port()
        app = Application([('/', HelloWorldHandler)])
        server = HTTPServer(app, io_loop=self.server_ioloop)
        server.add_socket(sock)

        self.server_thread = threading.Thread(target=self.server_ioloop.start)
        self.server_thread.start()

        self.http_client = HTTPClient() 
Example #18
Source File: httpserver_test.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
def test_missing_key(self):
        """A missing SSL key should cause an immediate exception."""

        application = Application()
        module_dir = os.path.dirname(__file__)
        existing_certificate = os.path.join(module_dir, 'test.crt')

        self.assertRaises(ValueError, HTTPServer, application, ssl_options={
                          "certfile": "/__mising__.crt",
                          })
        self.assertRaises(ValueError, HTTPServer, application, ssl_options={
                          "certfile": existing_certificate,
                          "keyfile": "/__missing__.key"
                          })

        # This actually works because both files exist
        HTTPServer(application, ssl_options={
                   "certfile": existing_certificate,
                   "keyfile": existing_certificate
                   }) 
Example #19
Source File: httpclient_test.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        if IOLoop.configured_class().__name__ == 'TwistedIOLoop':
            # TwistedIOLoop only supports the global reactor, so we can't have
            # separate IOLoops for client and server threads.
            raise unittest.SkipTest(
                'Sync HTTPClient not compatible with TwistedIOLoop')
        self.server_ioloop = IOLoop()

        sock, self.port = bind_unused_port()
        app = Application([('/', HelloWorldHandler)])
        server = HTTPServer(app, io_loop=self.server_ioloop)
        server.add_socket(sock)

        self.server_thread = threading.Thread(target=self.server_ioloop.start)
        self.server_thread.start()

        self.http_client = HTTPClient() 
Example #20
Source File: httpserver_test.py    From viewfinder with Apache License 2.0 6 votes vote down vote up
def test_unix_socket(self):
        sockfile = os.path.join(self.tmpdir, "test.sock")
        sock = netutil.bind_unix_socket(sockfile)
        app = Application([("/hello", HelloWorldRequestHandler)])
        server = HTTPServer(app, io_loop=self.io_loop)
        server.add_socket(sock)
        stream = IOStream(socket.socket(socket.AF_UNIX), io_loop=self.io_loop)
        stream.connect(sockfile, self.stop)
        self.wait()
        stream.write(b"GET /hello HTTP/1.0\r\n\r\n")
        stream.read_until(b"\r\n", self.stop)
        response = self.wait()
        self.assertEqual(response, b"HTTP/1.0 200 OK\r\n")
        stream.read_until(b"\r\n\r\n", self.stop)
        headers = HTTPHeaders.parse(self.wait().decode('latin1'))
        stream.read_bytes(int(headers["Content-Length"]), self.stop)
        body = self.wait()
        self.assertEqual(body, b"Hello world")
        stream.close()
        server.stop() 
Example #21
Source File: httpserver_test.py    From teleport with Apache License 2.0 6 votes vote down vote up
def test_missing_key(self):
        """A missing SSL key should cause an immediate exception."""

        application = Application()
        module_dir = os.path.dirname(__file__)
        existing_certificate = os.path.join(module_dir, 'test.crt')
        existing_key = os.path.join(module_dir, 'test.key')

        self.assertRaises((ValueError, IOError),
                          HTTPServer, application, ssl_options={
                              "certfile": "/__mising__.crt",
        })
        self.assertRaises((ValueError, IOError),
                          HTTPServer, application, ssl_options={
                              "certfile": existing_certificate,
                              "keyfile": "/__missing__.key"
        })

        # This actually works because both files exist
        HTTPServer(application, ssl_options={
                   "certfile": existing_certificate,
                   "keyfile": existing_key,
                   }) 
Example #22
Source File: httpclient_test.py    From teleport with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        if IOLoop.configured_class().__name__ == 'TwistedIOLoop':
            # TwistedIOLoop only supports the global reactor, so we can't have
            # separate IOLoops for client and server threads.
            raise unittest.SkipTest(
                'Sync HTTPClient not compatible with TwistedIOLoop')
        self.server_ioloop = IOLoop()

        @gen.coroutine
        def init_server():
            sock, self.port = bind_unused_port()
            app = Application([('/', HelloWorldHandler)])
            self.server = HTTPServer(app)
            self.server.add_socket(sock)
        self.server_ioloop.run_sync(init_server)

        self.server_thread = threading.Thread(target=self.server_ioloop.start)
        self.server_thread.start()

        self.http_client = HTTPClient() 
Example #23
Source File: testing.py    From teleport with Apache License 2.0 5 votes vote down vote up
def get_http_server(self) -> HTTPServer:
        return HTTPServer(self._app, **self.get_httpserver_options()) 
Example #24
Source File: httpserver_test.py    From teleport with Apache License 2.0 5 votes vote down vote up
def test_missing_arguments(self):
        application = Application()
        self.assertRaises(KeyError, HTTPServer, application, ssl_options={
            "keyfile": "/__missing__.crt",
        }) 
Example #25
Source File: httpserver_test.py    From viewfinder with Apache License 2.0 5 votes vote down vote up
def test_missing_arguments(self):
        application = Application()
        self.assertRaises(KeyError, HTTPServer, application, ssl_options={
            "keyfile": "/__missing__.crt",
        }) 
Example #26
Source File: httpserver_test.py    From teleport with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(UnixSocketTest, self).setUp()
        self.tmpdir = tempfile.mkdtemp()
        self.sockfile = os.path.join(self.tmpdir, "test.sock")
        sock = netutil.bind_unix_socket(self.sockfile)
        app = Application([("/hello", HelloWorldRequestHandler)])
        self.server = HTTPServer(app)
        self.server.add_socket(sock)
        self.stream = IOStream(socket.socket(socket.AF_UNIX))
        self.io_loop.run_sync(lambda: self.stream.connect(self.sockfile)) 
Example #27
Source File: testing.py    From teleport with Apache License 2.0 5 votes vote down vote up
def get_app(self) -> Application:
        """Should be overridden by subclasses to return a
        `tornado.web.Application` or other `.HTTPServer` callback.
        """
        raise NotImplementedError() 
Example #28
Source File: testing.py    From teleport with Apache License 2.0 5 votes vote down vote up
def get_http_server(self) -> HTTPServer:
        return HTTPServer(self._app, **self.get_httpserver_options()) 
Example #29
Source File: testing.py    From pySINDy with MIT License 5 votes vote down vote up
def get_http_server(self):
        return HTTPServer(self._app, **self.get_httpserver_options()) 
Example #30
Source File: app.py    From robotframework-hub with Apache License 2.0 5 votes vote down vote up
def start(self):
        """Start the app"""
        if self.args.debug:
            self.app.run(port=self.args.port, debug=self.args.debug, host=self.args.interface)
        else:
            root = "http://%s:%s" % (self.args.interface, self.args.port)
            print("tornado web server running on " + root)
            self.shutdown_requested = False
            http_server = HTTPServer(WSGIContainer(self.app))
            http_server.listen(port=self.args.port, address=self.args.interface)

            signal.signal(signal.SIGINT, self.signal_handler)
            tornado.ioloop.PeriodicCallback(self.check_shutdown_flag, 500).start()
            tornado.ioloop.IOLoop.instance().start()