Python tornado.httpserver.HTTPServer() Examples

The following are 30 code examples for showing how to use tornado.httpserver.HTTPServer(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module tornado.httpserver , or try the search function .

Example 1
Project: tornado-zh   Author: tao12345666333   File: httpclient_test.py    License: 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 2
Project: tornado-zh   Author: tao12345666333   File: httpserver_test.py    License: 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 3
Project: tornado-zh   Author: tao12345666333   File: httpserver_test.py    License: 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 4
Project: tornado-zh   Author: tao12345666333   File: httpserver_test.py    License: 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 5
Project: ServerMsgPush   Author: iakisey   File: __init__.py    License: 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 6
Project: opendevops   Author: opendevops-cn   File: httpclient_test.py    License: 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 7
Project: opendevops   Author: opendevops-cn   File: httpserver_test.py    License: 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 8
Project: torngas   Author: mqingyn   File: webserver.py    License: 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 9
Project: torngas   Author: mqingyn   File: webserver.py    License: 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 10
Project: Bast   Author: moluwole   File: bast.py    License: 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 11
Project: viewfinder   Author: viewfinderco   File: httpclient_test.py    License: 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 12
Project: viewfinder   Author: viewfinderco   File: httpserver_test.py    License: 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 13
Project: viewfinder   Author: viewfinderco   File: httpclient_test.py    License: 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 14
Project: viewfinder   Author: viewfinderco   File: httpserver_test.py    License: 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 15
Project: teleport   Author: tp4a   File: httpclient_test.py    License: 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 16
Project: teleport   Author: tp4a   File: httpserver_test.py    License: 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 17
Project: pySINDy   Author: luckystarufo   File: httpclient_test.py    License: 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 18
Project: pySINDy   Author: luckystarufo   File: httpserver_test.py    License: 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 19
Project: pypot   Author: poppy-project   File: snap.py    License: 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 20
Project: ATX   Author: NetEaseGame   File: __main__.py    License: 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 21
Project: tornado_http2   Author: bdarnell   File: benchmark.py    License: 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 22
Project: tornado-zh   Author: tao12345666333   File: s3server.py    License: MIT License 5 votes vote down vote up
def start(port, root_directory="/tmp/s3", bucket_depth=0):
    """Starts the mock S3 server on the given port at the given path."""
    application = S3Application(root_directory, bucket_depth)
    http_server = httpserver.HTTPServer(application)
    http_server.listen(port)
    ioloop.IOLoop.current().start() 
Example 23
Project: tornado-zh   Author: tao12345666333   File: testing.py    License: MIT License 5 votes vote down vote up
def get_http_server(self):
        return HTTPServer(self._app, io_loop=self.io_loop,
                          **self.get_httpserver_options()) 
Example 24
Project: tornado-zh   Author: tao12345666333   File: testing.py    License: MIT License 5 votes vote down vote up
def get_app(self):
        """Should be overridden by subclasses to return a
        `tornado.web.Application` or other `.HTTPServer` callback.
        """
        raise NotImplementedError() 
Example 25
Project: tornado-zh   Author: tao12345666333   File: httpserver_test.py    License: MIT License 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
Project: tornado-zh   Author: tao12345666333   File: httpserver_test.py    License: MIT License 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, io_loop=self.io_loop)
        self.server.add_socket(sock)
        self.stream = IOStream(socket.socket(socket.AF_UNIX), io_loop=self.io_loop)
        self.stream.connect(self.sockfile, self.stop)
        self.wait() 
Example 27
Project: tornado-zh   Author: tao12345666333   File: twisted_test.py    License: MIT License 5 votes vote down vote up
def start_tornado_server(self):
        class HelloHandler(RequestHandler):
            def get(self):
                self.write("Hello from tornado!")
        app = Application([('/', HelloHandler)],
                          log_function=lambda x: None)
        server = HTTPServer(app, io_loop=self.io_loop)
        sock, self.tornado_port = bind_unused_port()
        server.add_sockets([sock]) 
Example 28
Project: tornado-zh   Author: tao12345666333   File: testing.py    License: MIT License 5 votes vote down vote up
def get_http_server(self):
        return HTTPServer(self._app, io_loop=self.io_loop,
                          **self.get_httpserver_options()) 
Example 29
Project: tornado-zh   Author: tao12345666333   File: testing.py    License: MIT License 5 votes vote down vote up
def get_app(self):
        """Should be overridden by subclasses to return a
        `tornado.web.Application` or other `.HTTPServer` callback.
        """
        raise NotImplementedError() 
Example 30
Project: tornado-zh   Author: tao12345666333   File: httpserver_test.py    License: MIT License 5 votes vote down vote up
def test_missing_arguments(self):
        application = Application()
        self.assertRaises(KeyError, HTTPServer, application, ssl_options={
            "keyfile": "/__missing__.crt",
        })