Python wsgiref.simple_server.make_server() Examples

The following are 30 code examples of wsgiref.simple_server.make_server(). 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 wsgiref.simple_server , or try the search function .
Example #1
Source File: test_capture_http.py    From warcio with Apache License 2.0 7 votes vote down vote up
def setup_class(cls):
        from httpbin import app as httpbin_app

        cls.temp_dir = tempfile.mkdtemp('warctest')

        server = make_server('localhost', 0, httpbin_app)
        addr, cls.port = server.socket.getsockname()

        def run():
            try:
                server.serve_forever()
            except  Exception as e:
                print(e)

        thread = threading.Thread(target=run)
        thread.daemon = True
        thread.start()
        time.sleep(0.1) 
Example #2
Source File: serve.py    From pipenv with MIT License 6 votes vote down vote up
def __init__(self, host='127.0.0.1', port=0, application=None, **kwargs):
        self.app = application
        if self.port_envvar in os.environ:
            port = int(os.environ[self.port_envvar])
        self._server = make_server(
            host,
            port,
            self.app,
            handler_class=Handler,
            **kwargs
        )
        self.host = self._server.server_address[0]
        self.port = self._server.server_address[1]
        self.protocol = 'http'

        self._thread = threading.Thread(
            name=self.__class__,
            target=self._server.serve_forever,
        ) 
Example #3
Source File: api.py    From octavia with Apache License 2.0 6 votes vote down vote up
def main():
    gmr.TextGuruMeditation.setup_autorun(version)

    app = api_app.setup_app(argv=sys.argv)

    host = cfg.CONF.api_settings.bind_host
    port = cfg.CONF.api_settings.bind_port
    LOG.info("Starting API server on %(host)s:%(port)s",
             {"host": host, "port": port})
    if cfg.CONF.api_settings.auth_strategy != constants.KEYSTONE:
        LOG.warning('Octavia configuration [api_settings] auth_strategy is '
                    'not set to "keystone". This is not a normal '
                    'configuration and you may get "Missing project ID" '
                    'errors from API calls."')
    LOG.warning('You are running the Octavia API wsgi application using '
                'simple_server. We do not recommend this outside of simple '
                'testing. We recommend you run the Octavia API wsgi with '
                'a more full function server such as gunicorn or uWSGI.')
    srv = simple_server.make_server(host, port, app)

    srv.serve_forever() 
Example #4
Source File: __init__.py    From arnold-usd with Apache License 2.0 6 votes vote down vote up
def run(self, app): # pragma: no cover
        from wsgiref.simple_server import WSGIRequestHandler, WSGIServer
        from wsgiref.simple_server import make_server
        import socket

        class FixedHandler(WSGIRequestHandler):
            def address_string(self): # Prevent reverse DNS lookups please.
                return self.client_address[0]
            def log_request(*args, **kw):
                if not self.quiet:
                    return WSGIRequestHandler.log_request(*args, **kw)

        handler_cls = self.options.get('handler_class', FixedHandler)
        server_cls  = self.options.get('server_class', WSGIServer)

        if ':' in self.host: # Fix wsgiref for IPv6 addresses.
            if getattr(server_cls, 'address_family') == socket.AF_INET:
                class server_cls(server_cls):
                    address_family = socket.AF_INET6

        srv = make_server(self.host, self.port, app, server_cls, handler_cls)
        srv.serve_forever() 
Example #5
Source File: bottle.py    From aws-servicebroker with Apache License 2.0 6 votes vote down vote up
def run(self, app): # pragma: no cover
        from wsgiref.simple_server import WSGIRequestHandler, WSGIServer
        from wsgiref.simple_server import make_server
        import socket

        class FixedHandler(WSGIRequestHandler):
            def address_string(self): # Prevent reverse DNS lookups please.
                return self.client_address[0]
            def log_request(*args, **kw):
                if not self.quiet:
                    return WSGIRequestHandler.log_request(*args, **kw)

        handler_cls = self.options.get('handler_class', FixedHandler)
        server_cls  = self.options.get('server_class', WSGIServer)

        if ':' in self.host: # Fix wsgiref for IPv6 addresses.
            if getattr(server_cls, 'address_family') == socket.AF_INET:
                class server_cls(server_cls):
                    address_family = socket.AF_INET6

        srv = make_server(self.host, self.port, app, server_cls, handler_cls)
        srv.serve_forever() 
Example #6
Source File: wsgi.py    From slackbridge with GNU General Public License v3.0 6 votes vote down vote up
def builtin_httpd(address, port):
    from wsgiref.simple_server import make_server
    log.info('Starting builtin httpd...')
    server = make_server(address, port, application)
    try:
        server.serve_forever()
    except (KeyboardInterrupt, SystemExit):
        if RESPONSE_WORKER:
            log.debug('Stopping workers...')
            REQUEST_HANDLER.ipc.send(None)  # HAXX
            RESPONSE_WORKER.join()
        log.info('Finished...')


# Initialize subprocess immediately. Only use this if you use the uWSGI
# `lazy-apps` setting or have a single worker only! 
Example #7
Source File: ch13_e1_ex4.py    From Mastering-Object-Oriented-Python-Second-Edition with MIT License 6 votes vote down vote up
def auth_server(count: int = 1) -> None:
    from wsgiref.simple_server import make_server
    from wsgiref.validate import validator

    secure_app = Some_App()
    authenticated_app = Authenticate(users, secure_app)
    debug = validator(authenticated_app)
    httpd = make_server("", 8080, debug)
    if count is None:
        httpd.serve_forever()
    else:
        for c in range(count):
            httpd.handle_request()


# Demo 
Example #8
Source File: ch13_e1_ex4.py    From Mastering-Object-Oriented-Python-Second-Edition with MIT License 6 votes vote down vote up
def roulette_server_4(count: int = 1):
    from wsgiref.simple_server import make_server
    from wsgiref.validate import validator

    wheel = American()
    roulette = Roulette(wheel)
    debug = validator(roulette)
    httpd = make_server("", 8080, debug)
    if count is None:
        httpd.serve_forever()
    else:
        for c in range(count):
            httpd.handle_request()


# Client 
Example #9
Source File: bottle.py    From appengine-bottle-skeleton with Apache License 2.0 6 votes vote down vote up
def run(self, app): # pragma: no cover
        from wsgiref.simple_server import WSGIRequestHandler, WSGIServer
        from wsgiref.simple_server import make_server
        import socket

        class FixedHandler(WSGIRequestHandler):
            def address_string(self): # Prevent reverse DNS lookups please.
                return self.client_address[0]
            def log_request(*args, **kw):
                if not self.quiet:
                    return WSGIRequestHandler.log_request(*args, **kw)

        handler_cls = self.options.get('handler_class', FixedHandler)
        server_cls  = self.options.get('server_class', WSGIServer)

        if ':' in self.host: # Fix wsgiref for IPv6 addresses.
            if getattr(server_cls, 'address_family') == socket.AF_INET:
                class server_cls(server_cls):
                    address_family = socket.AF_INET6

        srv = make_server(self.host, self.port, app, server_cls, handler_cls)
        srv.serve_forever() 
Example #10
Source File: ch13_e1_ex3.py    From Mastering-Object-Oriented-Python-Second-Edition with MIT License 6 votes vote down vote up
def roulette_server_3(count: int = 1) -> None:
    from wsgiref.simple_server import make_server
    from wsgiref.validate import validator

    wheel = American(seed=1)
    roulette = Roulette(wheel)
    debug = validator(roulette)
    httpd = make_server("", 8080, debug)
    if count is None:
        httpd.serve_forever()
    else:
        for c in range(count):
            httpd.handle_request()


# Client 
Example #11
Source File: server_info_test.py    From tensorboard with Apache License 2.0 6 votes vote down vote up
def _start_server(self, app):
        """Starts a server and returns its origin ("http://localhost:PORT")."""
        (_, localhost) = _localhost()
        server_class = _make_ipv6_compatible_wsgi_server()
        server = simple_server.make_server(localhost, 0, app, server_class)
        executor = futures.ThreadPoolExecutor()
        future = executor.submit(server.serve_forever, poll_interval=0.01)

        def cleanup():
            server.shutdown()  # stop handling requests
            server.server_close()  # release port
            future.result(timeout=3)  # wait for server termination

        self.addCleanup(cleanup)
        if ":" in localhost and not localhost.startswith("["):
            # IPv6 IP address, probably "::1".
            localhost = "[%s]" % localhost
        return "http://%s:%d" % (localhost, server.server_port) 
Example #12
Source File: bottle.py    From opsbro with MIT License 6 votes vote down vote up
def run(self, app): # pragma: no cover
        from wsgiref.simple_server import WSGIRequestHandler, WSGIServer
        from wsgiref.simple_server import make_server
        import socket

        class FixedHandler(WSGIRequestHandler):
            def address_string(self): # Prevent reverse DNS lookups please.
                return self.client_address[0]
            def log_request(*args, **kw):
                if not self.quiet:
                    return WSGIRequestHandler.log_request(*args, **kw)

        handler_cls = self.options.get('handler_class', FixedHandler)
        server_cls  = self.options.get('server_class', WSGIServer)

        if ':' in self.host: # Fix wsgiref for IPv6 addresses.
            if getattr(server_cls, 'address_family') == socket.AF_INET:
                class server_cls(server_cls):
                    address_family = socket.AF_INET6

        srv = make_server(self.host, self.port, app, server_cls, handler_cls)
        srv.serve_forever() 
Example #13
Source File: bottle.py    From malwareHunter with GNU General Public License v2.0 6 votes vote down vote up
def run(self, app): # pragma: no cover
        from wsgiref.simple_server import WSGIRequestHandler, WSGIServer
        from wsgiref.simple_server import make_server
        import socket

        class FixedHandler(WSGIRequestHandler):
            def address_string(self): # Prevent reverse DNS lookups please.
                return self.client_address[0]
            def log_request(*args, **kw):
                if not self.quiet:
                    return WSGIRequestHandler.log_request(*args, **kw)

        handler_cls = self.options.get('handler_class', FixedHandler)
        server_cls  = self.options.get('server_class', WSGIServer)

        if ':' in self.host: # Fix wsgiref for IPv6 addresses.
            if getattr(server_cls, 'address_family') == socket.AF_INET:
                class server_cls(server_cls):
                    address_family = socket.AF_INET6

        srv = make_server(self.host, self.port, app, server_cls, handler_cls)
        srv.serve_forever() 
Example #14
Source File: bottle.py    From malwareHunter with GNU General Public License v2.0 6 votes vote down vote up
def run(self, app): # pragma: no cover
        from wsgiref.simple_server import WSGIRequestHandler, WSGIServer
        from wsgiref.simple_server import make_server
        import socket

        class FixedHandler(WSGIRequestHandler):
            def address_string(self): # Prevent reverse DNS lookups please.
                return self.client_address[0]
            def log_request(*args, **kw):
                if not self.quiet:
                    return WSGIRequestHandler.log_request(*args, **kw)

        handler_cls = self.options.get('handler_class', FixedHandler)
        server_cls  = self.options.get('server_class', WSGIServer)

        if ':' in self.host: # Fix wsgiref for IPv6 addresses.
            if getattr(server_cls, 'address_family') == socket.AF_INET:
                class server_cls(server_cls):
                    address_family = socket.AF_INET6

        srv = make_server(self.host, self.port, app, server_cls, handler_cls)
        srv.serve_forever() 
Example #15
Source File: bottle.py    From POC-EXP with GNU General Public License v3.0 5 votes vote down vote up
def run(self, app):  # pragma: no cover
        from wsgiref.simple_server import make_server
        from wsgiref.simple_server import WSGIRequestHandler, WSGIServer
        import socket

        class FixedHandler(WSGIRequestHandler):
            def address_string(self):  # Prevent reverse DNS lookups please.
                return self.client_address[0]

            def log_request(*args, **kw):
                if not self.quiet:
                    return WSGIRequestHandler.log_request(*args, **kw)

        handler_cls = self.options.get('handler_class', FixedHandler)
        server_cls = self.options.get('server_class', WSGIServer)

        if ':' in self.host:  # Fix wsgiref for IPv6 addresses.
            if getattr(server_cls, 'address_family') == socket.AF_INET:

                class server_cls(server_cls):
                    address_family = socket.AF_INET6

        self.srv = make_server(self.host, self.port, app, server_cls,
                               handler_cls)
        self.port = self.srv.server_port  # update port actual port (0 means random)
        try:
            self.srv.serve_forever()
        except KeyboardInterrupt:
            self.srv.server_close()  # Prevent ResourceWarning: unclosed socket
            raise 
Example #16
Source File: bottle.py    From annotated-py-projects with MIT License 5 votes vote down vote up
def run(self, handler):  # 重写 run() 函数.
        from wsgiref.simple_server import make_server

        srv = make_server(self.host, self.port, handler)  # 调用其他人写的库,所以这个代码,自己处理的内容很少.
        srv.serve_forever()  # 开启服务. 
Example #17
Source File: chromecast.py    From script.tubecast with MIT License 5 votes vote down vote up
def _run_server(self, host, port):
        self._server = make_server(host, port, app,
                                   server_class=ThreadedWSGIServer,
                                   handler_class=SilentWSGIRequestHandler)
        self._has_server.set()
        self._server.timeout = 0.1
        while not self._abort_var or not self._monitor.abortRequested():
            self._server.handle_request()

        self._server.server_close() 
Example #18
Source File: __init__.py    From aliyun-exporter with Apache License 2.0 5 votes vote down vote up
def main():
    signal.signal(signal.SIGTERM, signal_handler)
    logging.getLogger().setLevel(logging.INFO)

    parser = argparse.ArgumentParser(description="Aliyun CloudMonitor exporter for Prometheus.")
    parser.add_argument('-c', '--config-file', default='aliyun-exporter.yml',
                       help='path to configuration file.')
    parser.add_argument('-p', '--port', default=9525,
                        help='exporter exposed port')
    args = parser.parse_args()

    with open(args.config_file, 'r') as config_file:
        cfg = yaml.load(config_file, Loader=yaml.FullLoader)
    collector_config = CollectorConfig(**cfg)

    collector = AliyunCollector(collector_config)
    REGISTRY.register(collector)

    app = create_app(collector_config)

    logging.info("Start exporter, listen on {}".format(int(args.port)))
    httpd = make_server('', int(args.port), app)
    httpd.serve_forever()

    try:
        while True:
            time.sleep(5)
    except KeyboardInterrupt:
        pass 
Example #19
Source File: serve.py    From pecan with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _serve(self, app, conf):
        from wsgiref.simple_server import make_server

        host, port = conf.server.host, int(conf.server.port)
        srv = make_server(
            host,
            port,
            app,
            handler_class=PecanWSGIRequestHandler,
        )

        print('Starting server in PID %s' % os.getpid())

        if host == '0.0.0.0':
            print(
                'serving on 0.0.0.0:%s, view at http://127.0.0.1:%s' %
                (port, port)
            )
        else:
            print("serving on http://%s:%s" % (host, port))

        try:
            srv.serve_forever()
        except KeyboardInterrupt:
            # allow CTRL+C to shutdown
            pass 
Example #20
Source File: wsgi.py    From addok with MIT License 5 votes vote down vote up
def simple(args):
    from wsgiref.simple_server import make_server
    httpd = make_server(args.host, int(args.port), application)
    print("Serving HTTP on {}:{}…".format(args.host, args.port))
    try:
        httpd.serve_forever()
    except (KeyboardInterrupt, EOFError):
        print('Bye!') 
Example #21
Source File: bottle.py    From contrail-server-manager with Apache License 2.0 5 votes vote down vote up
def run(self, handler): # pragma: no cover
        from wsgiref.simple_server import make_server, WSGIRequestHandler
        if self.quiet:
            class QuietHandler(WSGIRequestHandler):
                def log_request(*args, **kw): pass
            self.options['handler_class'] = QuietHandler
        srv = make_server(self.host, self.port, handler, **self.options)
        srv.serve_forever() 
Example #22
Source File: web.py    From awesome-python3-webapp with GNU General Public License v2.0 5 votes vote down vote up
def run(self, port=9000, host='127.0.0.1'):
        from wsgiref.simple_server import make_server
        logging.info('application (%s) will start at %s:%s...' % (self._document_root, host, port))
        server = make_server(host, port, self.get_wsgi_application(debug=True))
        server.serve_forever() 
Example #23
Source File: exposition.py    From client_python with Apache License 2.0 5 votes vote down vote up
def start_wsgi_server(port, addr='', registry=REGISTRY):
    """Starts a WSGI server for prometheus metrics as a daemon thread."""
    app = make_wsgi_app(registry)
    httpd = make_server(addr, port, app, ThreadingWSGIServer, handler_class=_SilentHandler)
    t = threading.Thread(target=httpd.serve_forever)
    t.daemon = True
    t.start() 
Example #24
Source File: test_wsgiref.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def run_amock(app=hello_app, data="GET / HTTP/1.0\n\n"):
    server = make_server("", 80, app, MockServer, MockHandler)
    inp, out, err, olderr = StringIO(data), StringIO(), StringIO(), sys.stderr
    sys.stderr = err

    try:
        server.finish_request((inp,out), ("127.0.0.1",8888))
    finally:
        sys.stderr = olderr

    return out.getvalue(), err.getvalue() 
Example #25
Source File: rest_server_class.py    From warriorframework with Apache License 2.0 5 votes vote down vote up
def run(self, app):
        self.server = make_server(self.host, self.port, app)
        self.server.serve_forever() 
Example #26
Source File: bottle.py    From warriorframework with Apache License 2.0 5 votes vote down vote up
def run(self, app):  # pragma: no cover
        from wsgiref.simple_server import make_server
        from wsgiref.simple_server import WSGIRequestHandler, WSGIServer
        import socket

        class FixedHandler(WSGIRequestHandler):
            def address_string(self):  # Prevent reverse DNS lookups please.
                return self.client_address[0]

            def log_request(*args, **kw):
                if not self.quiet:
                    return WSGIRequestHandler.log_request(*args, **kw)

        handler_cls = self.options.get('handler_class', FixedHandler)
        server_cls = self.options.get('server_class', WSGIServer)

        if ':' in self.host:  # Fix wsgiref for IPv6 addresses.
            if getattr(server_cls, 'address_family') == socket.AF_INET:

                class server_cls(server_cls):
                    address_family = socket.AF_INET6

        self.srv = make_server(self.host, self.port, app, server_cls,
                               handler_cls)
        self.port = self.srv.server_port  # update port actual port (0 means random)
        try:
            self.srv.serve_forever()
        except KeyboardInterrupt:
            self.srv.server_close()  # Prevent ResourceWarning: unclosed socket
            raise 
Example #27
Source File: bottle.py    From warriorframework with Apache License 2.0 5 votes vote down vote up
def run(self, app): # pragma: no cover
        from wsgiref.simple_server import make_server
        from wsgiref.simple_server import WSGIRequestHandler, WSGIServer
        import socket

        class FixedHandler(WSGIRequestHandler):
            def address_string(self): # Prevent reverse DNS lookups please.
                return self.client_address[0]
            def log_request(*args, **kw):
                if not self.quiet:
                    return WSGIRequestHandler.log_request(*args, **kw)

        handler_cls = self.options.get('handler_class', FixedHandler)
        server_cls  = self.options.get('server_class', WSGIServer)

        if ':' in self.host: # Fix wsgiref for IPv6 addresses.
            if getattr(server_cls, 'address_family') == socket.AF_INET:
                class server_cls(server_cls):
                    address_family = socket.AF_INET6

        self.srv = make_server(self.host, self.port, app, server_cls, handler_cls)
        self.port = self.srv.server_port # update port actual port (0 means random)
        try:
            self.srv.serve_forever()
        except KeyboardInterrupt:
            self.srv.server_close() # Prevent ResourceWarning: unclosed socket
            raise 
Example #28
Source File: pytest_pyramid_server.py    From pytest-plugins with MIT License 5 votes vote down vote up
def start_server(self, env=None):
        """ Start the server instance.
        """
        print('\n==================================================================================')
        print("Starting wsgiref pyramid test server on host %s port %s" % (self.hostname, self.port))
        wsgi_app = loadapp('config:' + self.working_config)
        self.server = make_server(self.hostname, self.port, wsgi_app)
        worker = threading.Thread(target=self.server.serve_forever)
        worker.daemon = True
        worker.start()
        self.wait_for_go()
        print("Server now awake")
        print('==================================================================================') 
Example #29
Source File: webapp_test_util.py    From protorpc with Apache License 2.0 5 votes vote down vote up
def StartWebServer(self, port, application=None):
    """Start web server.

    Args:
      port: Port to start application on.
      application: Optional WSGI function.  If none provided will use
        tests CreateWsgiApplication method.

    Returns:
      A tuple (server, application):
        server: An instance of ServerThread.
        application: Application that web server responds with.
    """
    if not application:
      application = self.CreateWsgiApplication()
    validated_application = validate.validator(application)

    try:
      server = simple_server.make_server(
          'localhost', port, validated_application)
    except socket.error:
      # Try IPv6
      server = simple_server.make_server(
          'localhost', port, validated_application, server_class=WSGIServerIPv6)

    server = ServerThread(server)
    server.start()
    return server, application 
Example #30
Source File: vmservice.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def CreateServer(self):
    return simple_server.make_server(
        self._host, self._port, self._app,
        server_class=self._ThreadingWSGIServer)