Python http.server.SimpleHTTPRequestHandler() Examples

The following are 19 code examples of http.server.SimpleHTTPRequestHandler(). 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 http.server , or try the search function .
Example #1
Source File: conftest.py    From vue.py with MIT License 11 votes vote down vote up
def http_server():
    timeout = 10

    class RequestHandler(SimpleHTTPRequestHandler):
        protocol_version = "HTTP/1.0"

        def log_message(self, *args):
            pass

    with HTTPServer((Address, Port), RequestHandler) as httpd:
        thread = Thread(target=httpd.serve_forever, daemon=True)
        thread.start()

        c = HTTPConnection(Address, Port, timeout=timeout)
        c.request("GET", "/", "")
        assert c.getresponse().status == 200

        try:
            yield httpd
        finally:
            httpd.shutdown()
            thread.join(timeout=timeout) 
Example #2
Source File: conftest.py    From pytorch-lightning with Apache License 2.0 7 votes vote down vote up
def tmpdir_server(tmpdir):
    if sys.version_info >= (3, 7):
        Handler = partial(SimpleHTTPRequestHandler, directory=str(tmpdir))
        from http.server import ThreadingHTTPServer
    else:
        # unfortunately SimpleHTTPRequestHandler doesn't accept the directory arg in python3.6
        # so we have to hack it like this
        import os

        class Handler(SimpleHTTPRequestHandler):
            def translate_path(self, path):
                # get the path from cwd
                path = super().translate_path(path)
                # get the relative path
                relpath = os.path.relpath(path, os.getcwd())
                # return the full path from root_dir
                return os.path.join(str(tmpdir), relpath)

        # ThreadingHTTPServer was added in 3.7, so we need to define it ourselves
        from socketserver import ThreadingMixIn
        from http.server import HTTPServer

        class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
            daemon_threads = True

    with ThreadingHTTPServer(('localhost', 0), Handler) as server:
        server_thread = threading.Thread(target=server.serve_forever)
        # Exit the server thread when the main thread terminates
        server_thread.daemon = True
        server_thread.start()
        yield server.server_address
        server.shutdown() 
Example #3
Source File: serve.py    From ig with MIT License 6 votes vote down vote up
def run(self, open_immediately, port):
        '''
        Serves the `www` directory.

        Args:
            open_immediately: Whether to open the web browser immediately
            port: The port at which to serve the graph
        '''
        os.chdir(self.directory)
        handler = http.SimpleHTTPRequestHandler
        handler.extensions_map.update({
            '.webapp': 'application/x-web-app-manifest+json',
        })

        server = socketserver.TCPServer(('', port), handler)
        server.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        address = 'http://localhost:{0}/graph.html'.format(port)
        log.info('Serving at %s', address)

        if open_immediately:
            log.debug('Opening webbrowser')
            webbrowser.open(address)

        server.serve_forever() 
Example #4
Source File: base.py    From alibabacloud-python-sdk-v2 with Apache License 2.0 6 votes vote down vote up
def __enter__(self):
        class ServerHandler(SimpleHTTPRequestHandler):

            def do_GET(_self):
                _self.protocol_version = 'HTTP/1.1'
                self._headers = _self.headers
                self._url = _self.path
                _self.send_response(200)
                _self.send_header("Content-type", "application/json")
                _self.end_headers()
                _self.wfile.write(b"{}")

        self.server = HTTPServer(("", 51352), ServerHandler)

        def thread_func():
            self.server.serve_forever()

        thread = threading.Thread(target=thread_func)
        thread.start()
        return self 
Example #5
Source File: visualization.py    From bandicoot with MIT License 6 votes vote down vote up
def run(user, port=4242):
    """
    Build a temporary directory with a visualization and serve it over HTTP.

    Examples
    --------

        >>> bandicoot.visualization.run(U)
        Successfully exported the visualization to /tmp/tmpsIyncS
        Serving bandicoot visualization at http://0.0.0.0:4242
    """
    owd = os.getcwd()
    dir = export(user)
    os.chdir(dir)

    Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
    try:
        httpd = SocketServer.TCPServer(("", port), Handler)
        print("Serving bandicoot visualization at http://0.0.0.0:%i" % port)
        httpd.serve_forever()
    except KeyboardInterrupt:
        print("^C received, shutting down the web server")
        httpd.server_close()
    finally:
        os.chdir(owd) 
Example #6
Source File: httpd.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def is_gzip_accepted(self):
        accepted = set()
        for header in self.headers.get_all("Accept-Encoding"):
            # Then, you are allowed to specify a comma separated list of
            # acceptable encodings. You are also allowed to specify
            # 'encoding;q=XXX' to specify what encodings you would prefer.
            # We'll allow it to be set, but just ignore it.
            #   http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
            accepted.update(
                encoding.strip().split(";", 1)[0]
                for encoding in header.split(",")
            )
        return "gzip" in accepted

    # This is a copy & paste and minor modification of
    # SimpleHTTPRequestHandler's send_head code. Because to support
    # Content-Encoding gzip, we have to change what headers get returned (as it
    # affects Content-Length headers. 
Example #7
Source File: docs.py    From fastapi with MIT License 6 votes vote down vote up
def serve():
    """
    A quick server to preview a built site with translations.

    For development, prefer the command live (or just mkdocs serve).

    This is here only to preview a site with translations already built.

    Make sure you run the build-all command first.
    """
    typer.echo("Warning: this is a very simple server.")
    typer.echo("For development, use the command live instead.")
    typer.echo("This is here only to preview a site with translations already built.")
    typer.echo("Make sure you run the build-all command first.")
    os.chdir("site")
    server_address = ("", 8008)
    server = HTTPServer(server_address, SimpleHTTPRequestHandler)
    typer.echo(f"Serving at: http://127.0.0.1:8008")
    server.serve_forever() 
Example #8
Source File: package.py    From pex with Apache License 2.0 5 votes vote down vote up
def main(
  *additional_dist_formats: Format,
  verbosity: int = 0,
  local: bool = False,
  serve: bool = False
) -> None:
  pex_output_file = DIST_DIR / 'pex'
  print(f'Building Pex PEX to `{pex_output_file}` ...')
  build_pex_pex(pex_output_file, local, verbosity)

  git_rev = describe_git_rev()
  sha256, size = describe_file(pex_output_file)
  print(f'Built Pex PEX @ {git_rev}:')
  print(f'sha256: {sha256}')
  print(f'  size: {size}')

  if additional_dist_formats:
    print(f'Building additional distribution formats to `{DIST_DIR}`: '
        f'{", ".join(f"{i + 1}.) {fmt}" for i, fmt in enumerate(additional_dist_formats))} ...')
    build_pex_dists(*additional_dist_formats, verbose=verbosity > 0)
    print('Built:')
    for root, _, files in os.walk(DIST_DIR):
      root_path = Path(root)
      for f in files:
        dist_path = (root_path / f)
        if dist_path != pex_output_file:
          print(f'  {dist_path}')

  if serve:
    server = HTTPServer(('', 0), SimpleHTTPRequestHandler)
    host, port = server.server_address

    print(f'Serving Pex distributions from `{DIST_DIR}` at http://{host}:{port} ...')

    os.chdir(DIST_DIR)
    try:
      server.serve_forever()
    except KeyboardInterrupt:
      print(f'Server shut down in response to keyboard interrupt.') 
Example #9
Source File: simplehttpserver.py    From uiautomator2 with MIT License 5 votes vote down vote up
def main():
    PORT = free_port()
    Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
    httpd = SocketServer.TCPServer(("", PORT), Handler)

    # There is a bug that you have to refresh web page so you can see htmlreport
    # Even I tried to use threading to delay webbrowser open tab
    # but still need to refresh to let report show up.
    # I guess this is SimpleHTTPServer bug
    webbrowser.open('http://127.0.0.1:%d' % PORT, new=2)
    print("serving at port", PORT)
    httpd.serve_forever(0.1) 
Example #10
Source File: file_server.py    From cloudify-manager with Apache License 2.0 5 votes vote down vote up
def start_impl(self):
        os.chdir(self.root_path)

        class ReuseAddressTCPServer(TCPServer):
            allow_reuse_address = True
        httpd = ReuseAddressTCPServer(
            ('0.0.0.0', self.port), SimpleHTTPRequestHandler)
        httpd.serve_forever() 
Example #11
Source File: px.py    From px with MIT License 5 votes vote down vote up
def handle_one_request(self):
        try:
            httpserver.SimpleHTTPRequestHandler.handle_one_request(self)
        except socket.error as e:
            dprint("Socket error: %s" % e)
            if not hasattr(self, "_host_disconnected"):
                self._host_disconnected = 1
                dprint("Host disconnected")
            elif self._host_disconnected < State.max_disconnect:
                self._host_disconnected += 1
                dprint("Host disconnected: %d" % self._host_disconnected)
            else:
                dprint("Closed connection to avoid infinite loop")
                self.close_connection = True 
Example #12
Source File: policy_server.py    From ray with Apache License 2.0 5 votes vote down vote up
def _make_handler(external_env):
    class Handler(SimpleHTTPRequestHandler):
        def do_POST(self):
            content_len = int(self.headers.get("Content-Length"), 0)
            raw_body = self.rfile.read(content_len)
            parsed_input = pickle.loads(raw_body)
            try:
                response = self.execute_command(parsed_input)
                self.send_response(200)
                self.end_headers()
                self.wfile.write(pickle.dumps(response))
            except Exception:
                self.send_error(500, traceback.format_exc())

        def execute_command(self, args):
            command = args["command"]
            response = {}
            if command == PolicyClient.START_EPISODE:
                response["episode_id"] = external_env.start_episode(
                    args["episode_id"], args["training_enabled"])
            elif command == PolicyClient.GET_ACTION:
                response["action"] = external_env.get_action(
                    args["episode_id"], args["observation"])
            elif command == PolicyClient.LOG_ACTION:
                external_env.log_action(args["episode_id"],
                                        args["observation"], args["action"])
            elif command == PolicyClient.LOG_RETURNS:
                external_env.log_returns(args["episode_id"], args["reward"],
                                         args["info"])
            elif command == PolicyClient.END_EPISODE:
                external_env.end_episode(args["episode_id"],
                                         args["observation"])
            else:
                raise Exception("Unknown command: {}".format(command))
            return response

    return Handler 
Example #13
Source File: policy_server.py    From ray with Apache License 2.0 5 votes vote down vote up
def _make_handler(external_env):
    class Handler(SimpleHTTPRequestHandler):
        def do_POST(self):
            content_len = int(self.headers.get("Content-Length"), 0)
            raw_body = self.rfile.read(content_len)
            parsed_input = pickle.loads(raw_body)
            try:
                response = self.execute_command(parsed_input)
                self.send_response(200)
                self.end_headers()
                self.wfile.write(pickle.dumps(response))
            except Exception:
                self.send_error(500, traceback.format_exc())

        def execute_command(self, args):
            command = args["command"]
            response = {}
            if command == PolicyClient.START_EPISODE:
                response["episode_id"] = external_env.start_episode(
                    args["episode_id"], args["training_enabled"])
            elif command == PolicyClient.GET_ACTION:
                response["action"] = external_env.get_action(
                    args["episode_id"], args["observation"])
            elif command == PolicyClient.LOG_ACTION:
                external_env.log_action(args["episode_id"],
                                        args["observation"], args["action"])
            elif command == PolicyClient.LOG_RETURNS:
                external_env.log_returns(args["episode_id"], args["reward"],
                                         args["info"])
            elif command == PolicyClient.END_EPISODE:
                external_env.end_episode(args["episode_id"],
                                         args["observation"])
            else:
                raise Exception("Unknown command: {}".format(command))
            return response

    return Handler 
Example #14
Source File: ch15_ex2.py    From Functional-Python-Programming-Second-Edition with MIT License 5 votes vote down vote up
def server_demo():
    running = True
    httpd = HTTPServer(('localhost', 8080), SimpleHTTPRequestHandler)
    while running:
        httpd.handle_request()
    httpd.shutdown() 
Example #15
Source File: stats_server.py    From vprof with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, profile_json, *args, **kwargs):
        self._profile_json = profile_json
        self.uri_map = {
            '/': self._handle_root,
            '/profile': self._handle_profile,
        }
        # Since this class is old-style - call parent method directly.
        server.SimpleHTTPRequestHandler.__init__(
            self, *args, **kwargs) 
Example #16
Source File: reporters.py    From compare-mt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def launch_http_server(output_directory: str, bind_address:str ='0.0.0.0', bind_port: int=8000):
  assert Path(output_directory).is_dir()
  hostname = bind_address if bind_address != '0.0.0.0' else socket.gethostname()
  log.info(f'Directory = {output_directory}')
  log.info(f'Launching a web server:: http://{hostname}:{bind_port}/')
  Handler = partial(SimpleHTTPRequestHandler, directory=output_directory)
  server = HTTPServer(server_address=(bind_address, bind_port),
                               RequestHandlerClass=Handler)
  try:
    server.serve_forever()
  except KeyboardInterrupt:
    pass # all good! Exiting without printing stacktrace 
Example #17
Source File: mock_web_api_server.py    From python-slackclient with MIT License 5 votes vote down vote up
def __init__(self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler):
        threading.Thread.__init__(self)
        self.handler = handler
        self.test = test 
Example #18
Source File: mock_web_api_server.py    From python-slackclient with MIT License 5 votes vote down vote up
def __init__(self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler):
        threading.Thread.__init__(self)
        self.handler = handler
        self.test = test 
Example #19
Source File: mock_web_api_server.py    From python-slackclient with MIT License 5 votes vote down vote up
def __init__(self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler):
        threading.Thread.__init__(self)
        self.handler = handler
        self.test = test