Python werkzeug.serving.make_server() Examples

The following are 13 code examples of werkzeug.serving.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 werkzeug.serving , or try the search function .
Example #1
Source File: httpserver.py    From pytest-httpserver with MIT License 6 votes vote down vote up
def start(self):
        """
        Start the server in a thread.

        This method returns immediately (e.g. does not block), and it's the caller's
        responsibility to stop the server (by calling :py:meth:`stop`) when it is no longer needed).

        If the sever is not stopped by the caller and execution reaches the end, the
        program needs to be terminated by Ctrl+C or by signal as it will not terminate until
        the thred is stopped.

        If the sever is already running :py:class:`HTTPServerError` will be raised. If you are
        unsure, call :py:meth:`is_running` first.

        There's a context interface of this class which stops the server when the context block ends.
        """
        if self.is_running():
            raise HTTPServerError("Server is already running")

        self.server = make_server(self.host, self.port, self.application, ssl_context=self.ssl_context)
        self.port = self.server.port  # Update port (needed if `port` was set to 0)
        self.server_thread = threading.Thread(target=self.thread_target)
        self.server_thread.start() 
Example #2
Source File: flaskr.py    From ambianic-edge with Apache License 2.0 6 votes vote down vote up
def __init__(self, config):
        """Create Flask based web service."""
        self.config = config
        data_dir = None
        if config:
            data_dir = config.get('data_dir', None)
        if not data_dir:
            data_dir = DEFAULT_DATA_DIR
        self.srv = None
        app = create_app(data_dir=data_dir)
        ip_address = '0.0.0.0'
        port = 8778
        log.info('starting flask web server on %s:%d', ip_address, port)
        self.srv = make_server(ip_address, port, app)
        ctx = app.app_context()
        ctx.push()
        with app.app_context():
            flask.current_app.data_dir = data_dir
        self.flask_stopped = True
        log.debug('Flask process created') 
Example #3
Source File: __init__.py    From capybara.py with MIT License 6 votes vote down vote up
def init_werkzeug_server(app, port, host):
    try:
        import werkzeug
    except ImportError:
        raise ImportError(
            'Capybara\'s werkzeug server is unable to load `werkzeug`, please install the package '
            'and add `werkzeug` to your requirements.txt file.')

    from werkzeug.serving import make_server
    from logging import getLogger

    # Mute the server.
    log = getLogger('werkzeug')
    log.disabled = True

    server = make_server(host, port, app, threaded=True)

    # Inform Python that it shouldn't wait for request threads to terminate before
    # exiting. (They will still be appropriately terminated when the process exits.)
    server.daemon_threads = True

    server.serve_forever() 
Example #4
Source File: serving_util.py    From guildai with Apache License 2.0 6 votes vote down vote up
def make_server(host, port, app, logging=True):
    if host is None:
        raise RuntimeError("host cannot be None")
    if port is None:
        raise RuntimeError("port cannot be None")
    if logging:
        request_handler = serving.WSGIRequestHandler
    else:
        request_handler = QuietRequestHandler
    try:
        return serving.make_server(
            host, port, app, threaded=True, request_handler=request_handler
        )
    except socket.error as e:
        if host:
            raise
        log.debug(
            "error starting server on %s:%s (%s), " "trying IPv6 default host '::'",
            host,
            port,
            e,
        )
        return serving.make_server("::", port, app, threaded=True) 
Example #5
Source File: serving.py    From Flask with Apache License 2.0 6 votes vote down vote up
def run_dev_server(application):
    servers = []

    def tracking_make_server(*args, **kwargs):
        srv = real_make_server(*args, **kwargs)
        servers.append(srv)
        return srv
    serving.make_server = tracking_make_server
    try:
        t = Thread(target=serving.run_simple,
                   args=('localhost', 0, application))
        t.setDaemon(True)
        t.start()
        time.sleep(0.25)
    finally:
        serving.make_server = real_make_server
    if not servers:
        return None, None
    server, = servers
    ip, port = server.socket.getsockname()[:2]
    if ':' in ip:
        ip = '[%s]' % ip
    return server, '%s:%d'  % (ip, port) 
Example #6
Source File: serving.py    From Flask with Apache License 2.0 6 votes vote down vote up
def run_dev_server(application):
    servers = []

    def tracking_make_server(*args, **kwargs):
        srv = real_make_server(*args, **kwargs)
        servers.append(srv)
        return srv
    serving.make_server = tracking_make_server
    try:
        t = Thread(target=serving.run_simple,
                   args=('localhost', 0, application))
        t.setDaemon(True)
        t.start()
        time.sleep(0.25)
    finally:
        serving.make_server = real_make_server
    if not servers:
        return None, None
    server, = servers
    ip, port = server.socket.getsockname()[:2]
    if ':' in ip:
        ip = '[%s]' % ip
    return server, '%s:%d'  % (ip, port) 
Example #7
Source File: tensorboard_handle.py    From dataiku-contrib with Apache License 2.0 5 votes vote down vote up
def __init__(self, folder_name, host="127.0.0.1", verbosity=logging.WARN):
        Thread.__init__(self)
        self.project_key = os.environ["DKU_CURRENT_PROJECT_KEY"]
        self.folder_name = folder_name
        self.client = dataiku.api_client()

        logging.set_verbosity(verbosity)

        # Getting app
        logs_path = self.__get_logs_path()
        app = self.__get_tb_app(logs_path)

        # Setting server
        self.srv = make_server(host, 0, app) 
Example #8
Source File: tensorboard_handle.py    From dataiku-contrib with Apache License 2.0 5 votes vote down vote up
def __init__(self, folder_name, host="127.0.0.1", verbosity=logging.WARN):
        Thread.__init__(self)
        self.project_key = os.environ["DKU_CURRENT_PROJECT_KEY"]
        self.folder_name = folder_name
        self.client = dataiku.api_client()

        logging.set_verbosity(verbosity)

        # Getting app
        logs_path = self.__get_logs_path()
        app = self.__get_tb_app(logs_path)

        # Setting server
        self.srv = make_server(host, 0, app) 
Example #9
Source File: tfserve.py    From tfserve with MIT License 5 votes vote down vote up
def run(self, host, port, middleware=None):
        """Werkzeug run implementation.

        `middleware` may be provided as a function to handle
        requests. It must accept the arguments `(handler, req)` where
        `handler` is the TFServeApp request handler and `req` is the
        request.

        """
        app = self._init_app(middleware)
        server = serving.make_server(
            host, port, app, threaded=True,
            request_handler=serving.WSGIRequestHandler)
        server.serve_forever() 
Example #10
Source File: tests.py    From sanic-sentry with MIT License 5 votes vote down vote up
def __init__(self, *, host, port):
        self.host = host
        self.port = port
        self.app = flask.Flask('test')
        self.app.url_map.converters['everything'] = EverythingConverter

        self.srv = make_server(host=self.host, port=self.port, app=self.app)
        self.server_thread = threading.Thread(target=self.run, daemon=True) 
Example #11
Source File: tensorboard.py    From guildai with Apache License 2.0 5 votes vote down vote up
def make_simple_server(app, host, port):
    server = serving.make_server(host, port, app, threaded=True)
    server.daemon_threads = True
    server.handle_error = _handle_error
    tensorboard_url = "http://%s:%s" % (host, port)
    return server, tensorboard_url 
Example #12
Source File: tensorboard.py    From lambda-packs with MIT License 4 votes vote down vote up
def make_simple_server(tb_app, host, port):
  """Create an HTTP server for TensorBoard.

  Args:
    tb_app: The TensorBoard WSGI application to create a server for.
    host: Indicates the interfaces to bind to ('::' or '0.0.0.0' for all
        interfaces, '::1' or '127.0.0.1' for localhost). A blank value ('')
        indicates protocol-agnostic all interfaces.
    port: The port to bind to (0 indicates an unused port selected by the
        operating system).
  Returns:
    A tuple of (server, url):
      server: An HTTP server object configured to host TensorBoard.
      url: A best guess at a URL where TensorBoard will be accessible once the
        server has been started.
  Raises:
    socket.error: If a server could not be constructed with the host and port
      specified. Also logs an error message.
  """
  # Mute the werkzeug logging.
  base_logging.getLogger('werkzeug').setLevel(base_logging.WARNING)

  try:
    if host:
      # The user gave us an explicit host
      server = serving.make_server(host, port, tb_app, threaded=True)
      if ':' in host and not host.startswith('['):
        # Display IPv6 addresses as [::1]:80 rather than ::1:80
        final_host = '[{}]'.format(host)
      else:
        final_host = host
    else:
      # We've promised to bind to all interfaces on this host. However, we're
      # not sure whether that means IPv4 or IPv6 interfaces.
      try:
        # First try passing in a blank host (meaning all interfaces). This,
        # unfortunately, defaults to IPv4 even if no IPv4 interface is available
        # (yielding a socket.error).
        server = serving.make_server(host, port, tb_app, threaded=True)
      except socket.error:
        # If a blank host didn't work, we explicitly request IPv6 interfaces.
        server = serving.make_server('::', port, tb_app, threaded=True)
      final_host = socket.gethostname()
    server.daemon_threads = True
  except socket.error as socket_error:
    if port == 0:
      msg = 'TensorBoard unable to find any open port'
    else:
      msg = (
          'TensorBoard attempted to bind to port %d, but it was already in use'
          % FLAGS.port)
    logging.error(msg)
    print(msg)
    raise socket_error

  final_port = server.socket.getsockname()[1]
  tensorboard_url = 'http://%s:%d' % (final_host, final_port)
  return server, tensorboard_url 
Example #13
Source File: tensorboard_server.py    From tensorlang with Apache License 2.0 4 votes vote down vote up
def make_simple_server(tb_app, host, port):
  """Create an HTTP server for TensorBoard.

  Args:
    tb_app: The TensorBoard WSGI application to create a server for.
    host: Indicates the interfaces to bind to ('::' or '0.0.0.0' for all
        interfaces, '::1' or '127.0.0.1' for localhost). A blank value ('')
        indicates protocol-agnostic all interfaces.
    port: The port to bind to (0 indicates an unused port selected by the
        operating system).
  Returns:
    A tuple of (server, url):
      server: An HTTP server object configured to host TensorBoard.
      url: A best guess at a URL where TensorBoard will be accessible once the
        server has been started.
  Raises:
    socket.error: If a server could not be constructed with the host and port
      specified. Also logs an error message.
  """
  # Mute the werkzeug logging.
  base_logging.getLogger('werkzeug').setLevel(base_logging.WARNING)

  try:
    if host:
      # The user gave us an explicit host
      server = serving.make_server(host, port, tb_app, threaded=True)
      if ':' in host and not host.startswith('['):
        # Display IPv6 addresses as [::1]:80 rather than ::1:80
        final_host = '[{}]'.format(host)
      else:
        final_host = host
    else:
      # We've promised to bind to all interfaces on this host. However, we're
      # not sure whether that means IPv4 or IPv6 interfaces.
      try:
        # First try passing in a blank host (meaning all interfaces). This,
        # unfortunately, defaults to IPv4 even if no IPv4 interface is available
        # (yielding a socket.error).
        server = serving.make_server(host, port, tb_app, threaded=True)
      except socket.error:
        # If a blank host didn't work, we explicitly request IPv6 interfaces.
        server = serving.make_server('::', port, tb_app, threaded=True)
      final_host = socket.gethostname()
    server.daemon_threads = True
  except socket.error as socket_error:
    if port == 0:
      msg = 'TensorBoard unable to find any open port'
    else:
      msg = (
          'TensorBoard attempted to bind to port %d, but it was already in use'
          % port)
    logging.error(msg)
    print(msg)
    raise socket_error

  final_port = server.socket.getsockname()[1]
  tensorboard_url = 'http://%s:%d' % (final_host, final_port)
  return server, tensorboard_url