當前位置: 首頁>>代碼示例>>Python>>正文


Python server.SimpleHTTPRequestHandler方法代碼示例

本文整理匯總了Python中http.server.SimpleHTTPRequestHandler方法的典型用法代碼示例。如果您正苦於以下問題:Python server.SimpleHTTPRequestHandler方法的具體用法?Python server.SimpleHTTPRequestHandler怎麽用?Python server.SimpleHTTPRequestHandler使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在http.server的用法示例。


在下文中一共展示了server.SimpleHTTPRequestHandler方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: serve

# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 別名]
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() 
開發者ID:tiangolo,項目名稱:fastapi,代碼行數:21,代碼來源:docs.py

示例2: http_server

# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 別名]
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) 
開發者ID:stefanhoelzl,項目名稱:vue.py,代碼行數:24,代碼來源:conftest.py

示例3: is_gzip_accepted

# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 別名]
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. 
開發者ID:maas,項目名稱:maas,代碼行數:20,代碼來源:httpd.py

示例4: run

# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 別名]
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) 
開發者ID:computationalprivacy,項目名稱:bandicoot,代碼行數:27,代碼來源:visualization.py

示例5: __enter__

# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 別名]
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 
開發者ID:aliyun,項目名稱:alibabacloud-python-sdk-v2,代碼行數:22,代碼來源:base.py

示例6: run

# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 別名]
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() 
開發者ID:goldsborough,項目名稱:ig,代碼行數:27,代碼來源:serve.py

示例7: tmpdir_server

# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 別名]
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() 
開發者ID:PyTorchLightning,項目名稱:pytorch-lightning,代碼行數:34,代碼來源:conftest.py

示例8: __init__

# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 別名]
def __init__(self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler):
        threading.Thread.__init__(self)
        self.handler = handler
        self.test = test 
開發者ID:slackapi,項目名稱:python-slackclient,代碼行數:6,代碼來源:mock_web_api_server.py

示例9: __init__

# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 別名]
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) 
開發者ID:nvdv,項目名稱:vprof,代碼行數:11,代碼來源:stats_server.py

示例10: handle_one_request

# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 別名]
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 
開發者ID:genotrance,項目名稱:px,代碼行數:16,代碼來源:px.py

示例11: main

# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 別名]
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.') 
開發者ID:pantsbuild,項目名稱:pex,代碼行數:41,代碼來源:package.py

示例12: main

# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 別名]
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) 
開發者ID:openatx,項目名稱:uiautomator2,代碼行數:14,代碼來源:simplehttpserver.py

示例13: start_impl

# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 別名]
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() 
開發者ID:cloudify-cosmo,項目名稱:cloudify-manager,代碼行數:10,代碼來源:file_server.py

示例14: _make_handler

# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 別名]
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 
開發者ID:ray-project,項目名稱:ray,代碼行數:39,代碼來源:policy_server.py

示例15: server_demo

# 需要導入模塊: from http import server [as 別名]
# 或者: from http.server import SimpleHTTPRequestHandler [as 別名]
def server_demo():
    running = True
    httpd = HTTPServer(('localhost', 8080), SimpleHTTPRequestHandler)
    while running:
        httpd.handle_request()
    httpd.shutdown() 
開發者ID:PacktPublishing,項目名稱:Functional-Python-Programming-Second-Edition,代碼行數:8,代碼來源:ch15_ex2.py


注:本文中的http.server.SimpleHTTPRequestHandler方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。