Python six.moves.BaseHTTPServer.HTTPServer() Examples

The following are 30 code examples of six.moves.BaseHTTPServer.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 six.moves.BaseHTTPServer , or try the search function .
Example #1
Source File: server.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def BuildServer(multiplexer, host, port, logdir):
  """Sets up an HTTP server for running TensorBoard.

  Args:
    multiplexer: An `EventMultiplexer` that the server will query for
      information about events.
    host: The host name.
    port: The port number to bind to, or 0 to pick one automatically.
    logdir: The logdir argument string that tensorboard started up with.
  Returns:
    A `BaseHTTPServer.HTTPServer`.
  """
  names_to_plugins = {'projector': projector_plugin.ProjectorPlugin()}
  factory = functools.partial(handler.TensorboardHandler, multiplexer,
                              names_to_plugins, logdir)
  return ThreadedHTTPServer((host, port), factory) 
Example #2
Source File: server.py    From keras-lambda with MIT License 6 votes vote down vote up
def BuildServer(multiplexer, host, port, logdir):
  """Sets up an HTTP server for running TensorBoard.

  Args:
    multiplexer: An `EventMultiplexer` that the server will query for
      information about events.
    host: The host name.
    port: The port number to bind to, or 0 to pick one automatically.
    logdir: The logdir argument string that tensorboard started up with.
  Returns:
    A `BaseHTTPServer.HTTPServer`.
  """
  names_to_plugins = {'projector': projector_plugin.ProjectorPlugin()}
  factory = functools.partial(handler.TensorboardHandler, multiplexer,
                              names_to_plugins, logdir)
  return ThreadedHTTPServer((host, port), factory) 
Example #3
Source File: utils.py    From django-cas-server with GNU General Public License v3.0 6 votes vote down vote up
def run(cls, service, ticket, username, attributes, port=0):
        """Run a BaseHTTPServer using this class as handler"""
        server_class = BaseHTTPServer.HTTPServer
        httpd = server_class(("127.0.0.1", port), cls)
        httpd.service = service
        httpd.ticket = ticket
        httpd.username = username
        httpd.attributes = attributes
        (host, port) = httpd.socket.getsockname()

        def lauch():
            """routine to lauch in a background thread"""
            httpd.handle_request()
            httpd.server_close()

        httpd_thread = Thread(target=lauch)
        httpd_thread.daemon = True
        httpd_thread.start()
        return (httpd, host, port) 
Example #4
Source File: test_seleniumrequests.py    From Selenium-Requests with MIT License 6 votes vote down vote up
def run_http_server(request_handler_class):
    while True:
        port = get_unused_port()
        try:
            server = BaseHTTPServer.HTTPServer(('', port), request_handler_class)
            break
        except socket.error:
            pass

    def run():
        while True:
            server.handle_request()

    thread = threading.Thread(target=run)
    thread.daemon = True
    thread.start()

    return 'http://127.0.0.1:%d/' % port 
Example #5
Source File: auth_server.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def handle_rpc(self, method, request):
    """Called by _RequestHandler to handle one RPC call.

    Called from internal server thread. May be called even if the server is
    already stopped (due to BaseHTTPServer.HTTPServer implementation that
    stupidly leaks handler threads).

    Args:
      method: name of the invoked RPC method, e.g. "GetOAuthToken".
      request: JSON dict with the request body.

    Returns:
      JSON dict with the response body.

    Raises:
      RPCError to return non-200 HTTP code and an error message as plain text.
    """
    if method == 'GetOAuthToken':
      return self.handle_get_oauth_token(request)
    raise RPCError(404, 'Unknown RPC method "%s".' % method)

  ### RPC method handlers. Called from internal threads. 
Example #6
Source File: server.py    From testplan with Apache License 2.0 6 votes vote down vote up
def run(self):
        """Start the HTTP server thread."""
        self.server = http_server.HTTPServer(
            server_address=(self.host, self.port),
            RequestHandlerClass=self.request_handler,
        )
        self.server.requests = self.requests_queue
        self.server.responses = self.responses_queue
        self.server.handler_attributes = self.handler_attributes
        self.server.timeout = self.timeout
        self.server.interval = self.interval
        nothing = lambda msg: None
        self.server.log_callback = (
            self.logger.debug if self.logger else nothing
        )
        self.server.serve_forever() 
Example #7
Source File: server.py    From testplan with Apache License 2.0 6 votes vote down vote up
def __init__(
        self,
        name,
        host="localhost",
        port=0,
        request_handler=HTTPRequestHandler,
        handler_attributes=None,
        timeout=5,
        interval=0.01,
        **options
    ):
        options.update(self.filter_locals(locals()))
        super(HTTPServer, self).__init__(**options)
        self._host = None
        self._port = None
        self.request_handler = None
        self.handler_attributes = None
        self.timeout = None
        self.interval = None
        self.requests = None
        self.responses = None
        self._server_thread = None
        self._logname = "{0}.log".format(slugify(self.cfg.name)) 
Example #8
Source File: server.py    From testplan with Apache License 2.0 6 votes vote down vote up
def _parse_request(self):
        """
        Put the request into the HTTPServer's requests queue. Get the response
        from the HTTPServer's response queue. If there is no response send an
        error message back.

        :return: ``None``
        :rtype: ``NoneType``
        """
        response = self.get_response(request=self.path)
        if not isinstance(response, HTTPResponse):
            raise TypeError("Response must be of type HTTPResponse")

        self._send_header(
            status_code=response.status_code, headers=response.headers
        )
        self._send_content(response.content)
        self.server.log_callback(
            "Sent response with:\n  status code {}\n  headers {}".format(
                response.status_code, response.headers
            )
        ) 
Example #9
Source File: local.py    From chalice with Apache License 2.0 5 votes vote down vote up
def __init__(self, request, client_address, server, app_object, config):
        # type: (bytes, Tuple[str, int], HTTPServer, Chalice, Config) -> None
        self.local_gateway = LocalGateway(app_object, config)
        BaseHTTPRequestHandler.__init__(
            self, request, client_address, server)  # type: ignore 
Example #10
Source File: THttpServer.py    From ajs2 with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self,
                 processor,
                 server_address,
                 inputProtocolFactory,
                 outputProtocolFactory=None,
                 server_class=BaseHTTPServer.HTTPServer):
        """Set up protocol factories and HTTP server.

        See BaseHTTPServer for server_address.
        See TServer for protocol factories.
        """
        if outputProtocolFactory is None:
            outputProtocolFactory = inputProtocolFactory

        TServer.TServer.__init__(self, processor, None, None, None,
                                 inputProtocolFactory, outputProtocolFactory)

        thttpserver = self

        class RequestHander(BaseHTTPServer.BaseHTTPRequestHandler):
            def do_POST(self):
                # Don't care about the request path.
                itrans = TTransport.TFileObjectTransport(self.rfile)
                otrans = TTransport.TFileObjectTransport(self.wfile)
                itrans = TTransport.TBufferedTransport(
                    itrans, int(self.headers['Content-Length']))
                otrans = TTransport.TMemoryBuffer()
                iprot = thttpserver.inputProtocolFactory.getProtocol(itrans)
                oprot = thttpserver.outputProtocolFactory.getProtocol(otrans)
                try:
                    thttpserver.processor.process(iprot, oprot)
                except ResponseException as exn:
                    exn.handler(self)
                else:
                    self.send_response(200)
                    self.send_header("content-type", "application/x-thrift")
                    self.end_headers()
                    self.wfile.write(otrans.getvalue())

        self.httpd = server_class(server_address, RequestHander) 
Example #11
Source File: auth_server.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def __init__(self, local_auth_server, addr):
    BaseHTTPServer.HTTPServer.__init__(self, addr, _RequestHandler)
    self.local_auth_server = local_auth_server 
Example #12
Source File: auth_server.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def serve_forever(self, poll_interval=None):
    """Overrides default poll interval."""
    BaseHTTPServer.HTTPServer.serve_forever(
        self, poll_interval or self.poll_interval) 
Example #13
Source File: THttpServer.py    From SOLO with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self,
                 processor,
                 server_address,
                 inputProtocolFactory,
                 outputProtocolFactory=None,
                 server_class=BaseHTTPServer.HTTPServer):
        if outputProtocolFactory is None:
            outputProtocolFactory = inputProtocolFactory
        TServer.TServer.__init__(self, processor, None, None, None,
                                 inputProtocolFactory, outputProtocolFactory)
        thttpserver = self
        class RequestHander(BaseHTTPServer.BaseHTTPRequestHandler):
            def do_POST(self):
                itrans = TTransport.TFileObjectTransport(self.rfile)
                otrans = TTransport.TFileObjectTransport(self.wfile)
                itrans = TTransport.TBufferedTransport(
                    itrans, int(self.headers['Content-Length']))
                otrans = TTransport.TMemoryBuffer()
                iprot = thttpserver.inputProtocolFactory.getProtocol(itrans)
                oprot = thttpserver.outputProtocolFactory.getProtocol(otrans)
                try:
                    thttpserver.processor.process(iprot, oprot)
                except ResponseException as exn:
                    exn.handler(self)
                else:
                    self.send_response(200)
                    self.send_header("content-type", "application/x-thrift")
                    self.end_headers()
                    self.wfile.write(otrans.getvalue())
        self.httpd = server_class(server_address, RequestHander) 
Example #14
Source File: oauth2.py    From spotipy with MIT License 5 votes vote down vote up
def start_local_http_server(port, handler=RequestHandler):
    server = HTTPServer(("127.0.0.1", port), handler)
    server.allow_reuse_address = True
    server.auth_code = None
    server.auth_token_form = None
    server.error = None
    return server 
Example #15
Source File: request.py    From Selenium-Requests with MIT License 5 votes vote down vote up
def get_webdriver_request_headers(webdriver):
    # There's a small chance that the port was taken since the call of get_unused_port(), so make sure we try as often
    # as needed
    while True:
        port = get_unused_port()
        try:
            server = BaseHTTPServer.HTTPServer(('', port), HTTPRequestHandler)
            break
        except socket.error:
            pass

    threading.Thread(target=server.handle_request).start()
    original_window_handle = webdriver.current_window_handle
    webdriver.execute_script("window.open('http://127.0.0.1:%d/', '_blank');" % port)

    update_headers_mutex.acquire()

    # Not optional: Make sure that the webdriver didn't switch the window handle to the newly opened window. Behaviors
    # of different webdrivers seem to differ here. Workaround for Firefox: If a new window is opened via JavaScript as a
    # new tab, requesting self.current_url never returns. Explicitly switching to the current window handle again seems
    # to fix this issue.
    webdriver.switch_to.window(original_window_handle)

    global headers
    headers_ = headers
    headers = None

    # Remove the host header, which will simply contain the localhost address of the HTTPRequestHandler instance
    del headers_['host']
    return headers_ 
Example #16
Source File: oauth.py    From ttrv with MIT License 5 votes vote down vote up
def handle_error(self, request, client_address):
        """
        The default HTTPServer's error handler prints the request traceback
        to stdout, which breaks the curses display.

        Override it to log to a file instead.
        """
        _logger.exception('Error processing request in OAuth HTTP Server') 
Example #17
Source File: test_local.py    From chalice with Apache License 2.0 5 votes vote down vote up
def test_can_delegate_to_server(self, sample_app):
        http_server = mock.Mock(spec=HTTPServer)
        dev_server = LocalDevServer(
            sample_app, Config(), '0.0.0.0', 8000,
            server_cls=lambda *args: http_server,
        )

        dev_server.handle_single_request()
        http_server.handle_request.assert_called_with()

        dev_server.serve_forever()
        http_server.serve_forever.assert_called_with() 
Example #18
Source File: utils.py    From django-cas-server with GNU General Public License v3.0 5 votes vote down vote up
def run(cls, port=0):
        """Run a BaseHTTPServer using this class as handler"""
        server_class = BaseHTTPServer.HTTPServer
        httpd = server_class(("127.0.0.1", port), cls)
        (host, port) = httpd.socket.getsockname()

        def lauch():
            """routine to lauch in a background thread"""
            httpd.handle_request()
            httpd.server_close()

        httpd_thread = Thread(target=lauch)
        httpd_thread.daemon = True
        httpd_thread.start()
        return (httpd, host, port) 
Example #19
Source File: annotator.py    From python-stanford-corenlp with MIT License 5 votes vote down vote up
def run(self):
        """
        Runs the server using Python's simple HTTPServer.
        TODO: make this multithreaded.
        """
        httpd = HTTPServer((self.host, self.port), self._Handler)
        sa = httpd.socket.getsockname()
        serve_message = "Serving HTTP on {host} port {port} (http://{host}:{port}/) ..."
        print(serve_message.format(host=sa[0], port=sa[1]))
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\nKeyboard interrupt received, exiting.")
            httpd.shutdown() 
Example #20
Source File: THttpServer.py    From thrift with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self,
                 processor,
                 server_address,
                 inputProtocolFactory,
                 outputProtocolFactory=None,
                 server_class=BaseHTTPServer.HTTPServer):
        if outputProtocolFactory is None:
            outputProtocolFactory = inputProtocolFactory
        TServer.TServer.__init__(self, processor, None, None, None,
                                 inputProtocolFactory, outputProtocolFactory)
        thttpserver = self
        class RequestHander(BaseHTTPServer.BaseHTTPRequestHandler):
            def do_POST(self):
                itrans = TTransport.TFileObjectTransport(self.rfile)
                otrans = TTransport.TFileObjectTransport(self.wfile)
                itrans = TTransport.TBufferedTransport(
                    itrans, int(self.headers['Content-Length']))
                otrans = TTransport.TMemoryBuffer()
                iprot = thttpserver.inputProtocolFactory.getProtocol(itrans)
                oprot = thttpserver.outputProtocolFactory.getProtocol(otrans)
                try:
                    thttpserver.processor.process(iprot, oprot)
                except ResponseException as exn:
                    exn.handler(self)
                else:
                    self.send_response(200)
                    self.send_header("content-type", "application/x-thrift")
                    self.end_headers()
                    self.wfile.write(otrans.getvalue())
        self.httpd = server_class(server_address, RequestHander) 
Example #21
Source File: oauth.py    From rtv with MIT License 5 votes vote down vote up
def handle_error(self, request, client_address):
        """
        The default HTTPServer's error handler prints the request traceback
        to stdout, which breaks the curses display.

        Override it to log to a file instead.
        """
        _logger.exception('Error processing request in OAuth HTTP Server') 
Example #22
Source File: test_spark.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def run_ssl_server():
    cert_file = os.path.join(CERTIFICATE_DIR, 'server.pem')

    httpd = BaseHTTPServer.HTTPServer((SSL_SERVER_ADDRESS, SSL_SERVER_PORT), StandaloneAppsResponseHandler)
    httpd.socket = ssl.wrap_socket(httpd.socket, certfile=cert_file, server_side=False)
    httpd.timeout = 5

    threading.Thread(target=httpd.handle_request).start()
    time.sleep(0.5)
    return httpd 
Example #23
Source File: pytest_plugin.py    From ftw with Apache License 2.0 5 votes vote down vote up
def http_serv_obj():
    """
    Return an HTTP object listening on localhost port 80 for testing
    """
    return HTTPServer(('localhost', 80), SimpleHTTPRequestHandler) 
Example #24
Source File: THttpServer.py    From Aditmadzs2 with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self,
                 processor,
                 server_address,
                 inputProtocolFactory,
                 outputProtocolFactory=None,
                 server_class=BaseHTTPServer.HTTPServer):
        """Set up protocol factories and HTTP server.

        See BaseHTTPServer for server_address.
        See TServer for protocol factories.
        """
        if outputProtocolFactory is None:
            outputProtocolFactory = inputProtocolFactory

        TServer.TServer.__init__(self, processor, None, None, None,
                                 inputProtocolFactory, outputProtocolFactory)

        thttpserver = self

        class RequestHander(BaseHTTPServer.BaseHTTPRequestHandler):
            def do_POST(self):
                # Don't care about the request path.
                itrans = TTransport.TFileObjectTransport(self.rfile)
                otrans = TTransport.TFileObjectTransport(self.wfile)
                itrans = TTransport.TBufferedTransport(
                    itrans, int(self.headers['Content-Length']))
                otrans = TTransport.TMemoryBuffer()
                iprot = thttpserver.inputProtocolFactory.getProtocol(itrans)
                oprot = thttpserver.outputProtocolFactory.getProtocol(otrans)
                try:
                    thttpserver.processor.process(iprot, oprot)
                except ResponseException as exn:
                    exn.handler(self)
                else:
                    self.send_response(200)
                    self.send_header("content-type", "application/x-thrift")
                    self.end_headers()
                    self.wfile.write(otrans.getvalue())

        self.httpd = server_class(server_address, RequestHander) 
Example #25
Source File: server.py    From testplan with Apache License 2.0 5 votes vote down vote up
def get_request(self):
        """
        Get a request sent to the HTTPServer, if the requests queue is empty
        return None.

        :return: A request from the queue or ``None``
        :rtype: ``str`` or ``NoneType``
        """
        try:
            return self.requests.get(False)
        except queue.Empty:
            return None 
Example #26
Source File: server.py    From testplan with Apache License 2.0 5 votes vote down vote up
def _stop(self):
        """Stop the HTTPServer."""
        if self._server_thread:
            self._server_thread.stop() 
Example #27
Source File: server.py    From testplan with Apache License 2.0 5 votes vote down vote up
def stopping(self):
        """Stop the HTTPServer."""
        super(HTTPServer, self).stopping()
        self._stop()
        self.file_logger.debug("Stopped HTTPServer.")
        self._close_file_logger() 
Example #28
Source File: server.py    From testplan with Apache License 2.0 5 votes vote down vote up
def aborting(self):
        """Abort logic that stops the server."""
        self._stop()
        self.file_logger.debug("Aborted HTTPServer.") 
Example #29
Source File: server.py    From testplan with Apache License 2.0 5 votes vote down vote up
def logpath(self):
        """HTTPServer logfile in runpath."""
        return os.path.join(self.runpath, self._logname) 
Example #30
Source File: test_http.py    From testplan with Apache License 2.0 5 votes vote down vote up
def http_server():
    """
    Yields an HTTP server object, which stores JSON data from received POST
    requests in a .post_data queue.
    """
    PostHandler.post_data = []
    server = HTTPServer(("", 0), PostHandler)
    start_thread = threading.Thread(target=server.serve_forever)
    start_thread.daemon = True
    start_thread.start()

    yield server

    server.shutdown()
    start_thread.join()