Python http.server.serve_forever() Examples

The following are 13 code examples of http.server.serve_forever(). 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: advancedhttpserver.py    From AdvancedHTTPServer with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setUp(self):
		RegisterPath("^{0}$".format(self.test_resource[1:]), self.handler_class.__name__)(self._test_resource_handler)
		self.server = self.server_class(self.handler_class, **self._server_kwargs)
		self.assertTrue(isinstance(self.server, AdvancedHTTPServer))
		self.server_thread = threading.Thread(target=self.server.serve_forever)
		self.server_thread.daemon = True
		self.server_thread.start()
		self.assertTrue(self.server_thread.is_alive())
		self.shutdown_requested = False
		if len(self.server_address) == 3 and self.server_address[2]:
			context = ssl.create_default_context()
			context.check_hostname = False
			context.verify_mode = ssl.CERT_NONE
			self.http_connection = http.client.HTTPSConnection(self.server_address[0], self.server_address[1], context=context)
		else:
			self.http_connection = http.client.HTTPConnection(self.server_address[0], self.server_address[1])
		self.http_connection.connect() 
Example #2
Source File: advancedhttpserver.py    From AdvancedHTTPServer with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
	try:
		server = build_server_from_argparser()
	except ImportError:
		server = AdvancedHTTPServer(RequestHandler, use_threads=False)
		server.serve_files_root = '.'

	server.serve_files_root = (server.serve_files_root or '.')
	server.serve_files = True
	try:
		server.serve_forever()
	except KeyboardInterrupt:
		pass
	server.shutdown()
	logging.shutdown()
	return 0 
Example #3
Source File: serving.py    From pywebview with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_wsgi_server(app):
    if hasattr(app, '__webview_url'):
        # It's already been spun up and is running
        return app.__webview_url

    port = _get_random_port()
    server = wsgiref.simple_server.make_server(
        'localhost', port, app, server_class=ThreadingWSGIServer,
        handler_class=WSGIRequestHandler11,
    )

    t = threading.Thread(target=server.serve_forever)
    t.daemon = True
    t.start()

    app.__webview_url = 'http://localhost:{0}/'.format(port)
    logger.debug('HTTP server for {!r} started on {}'.format(app, app.__webview_url))

    return app.__webview_url 
Example #4
Source File: advancedhttpserver.py    From AdvancedHTTPServer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def serve_forever(self, fork=False):
		"""
		Start handling requests. This method must be called and does not
		return unless the :py:meth:`.shutdown` method is called from
		another thread.

		:param bool fork: Whether to fork or not before serving content.
		:return: The child processes PID if *fork* is set to True.
		:rtype: int
		"""
		if fork:
			if not hasattr(os, 'fork'):
				raise OSError('os.fork is not available')
			child_pid = os.fork()
			if child_pid != 0:
				self.logger.info('forked child process: ' + str(child_pid))
				return child_pid
		self.__server_thread = threading.current_thread()
		self.__wakeup_fd = WakeupFd()
		self.__is_shutdown.clear()
		self.__should_stop.clear()
		self.__is_running.set()
		while not self.__should_stop.is_set():
			try:
				self._serve_ready()
			except socket.error:
				self.logger.warning('encountered socket error, stopping server')
				self.__should_stop.set()
		self.__is_shutdown.set()
		self.__is_running.clear()
		return 0 
Example #5
Source File: servertools.py    From hydpy with GNU Lesser General Public License v3.0 5 votes vote down vote up
def start_server(socket, projectname, xmlfilename: str) -> None:
    """Start the *HydPy* server using the given socket.

    The folder with the given `projectname` must be available within the
    current working directory.  The XML configuration file must be placed
    within the project folder unless `xmlfilename` is an absolute file path.
    The XML configuration file must be valid concerning the schema file
    `HydPyConfigMultipleRuns.xsd` (see method |ServerState.initialise|
    for further information).

    Note that function |start_server| tries to read the "mime types" from
    a dictionary stored in the file `mimetypes.txt` available in subpackage
    `conf`, and passes it as attribute `extension_map` to class |HydPyServer|.
    The reason is to avoid the long computation time of function
    |mimetypes.init| of module |mimetypes|, usually called when defining
    class `BaseHTTPRequestHandler` of module `http.server`.  If file
    `mimetypes.txt` does not exist or does not work for some reasons,
    |start_server| calls |mimetypes.init| as usual, (over)writes
    `mimetypes.txt`, and tries to proceed as expected.
    """
    filepath = os.path.join(conf.__path__[0], 'mimetypes.txt')
    try:
        with open(filepath) as file_:
            dict_ = eval(open(file_.read()))
    except BaseException:
        mimetypes.init()
        dict_ = mimetypes.types_map.copy()
        dict_.update({
            '': 'application/octet-stream',
            '.py': 'text/plain',
            '.c': 'text/plain',
            '.h': 'text/plain',
            })
        with open(filepath, 'w') as file_:
            file_.write(str(dict_))
    HydPyServer.extensions_map = dict_
    state.initialise(projectname, xmlfilename)
    server = http.server.HTTPServer(('', int(socket)), HydPyServer)
    server.serve_forever() 
Example #6
Source File: rasterize_test.py    From content with MIT License 5 votes vote down vote up
def http_wait_server():
    # Simple http handler which waits 10 seconds before responding
    class WaitHanlder(http.server.BaseHTTPRequestHandler):

        def do_HEAD(self):
            self.send_response(200)
            self.send_header("Content-type", "text/html")
            self.end_headers()

        def do_GET(self):
            time.sleep(10)
            try:
                self.send_response(200)
                self.send_header("Content-type", "text/html")
                self.end_headers()
                self.wfile.write(bytes("<html><head><title>Test wait handler</title></head>"
                                       "<body><p>Test Wait</p></body></html>", 'utf-8'))
                self.flush_headers()
            except BrokenPipeError:  # ignore broken pipe as socket might have been closed
                pass

        # disable logging

        def log_message(self, format, *args):
            pass

    with http.server.ThreadingHTTPServer(('', 10888), WaitHanlder) as server:
        server_thread = threading.Thread(target=server.serve_forever)
        server_thread.start()
        yield
        server.shutdown()
        server_thread.join()


# Some web servers can block the connection after the http is sent
# In this case chromium will hang. An example for this is:
# curl -v -H 'user-agent: HeadlessChrome' --max-time 10  "http://www.grainger.com/"  # disable-secrets-detection
# This tests access a server which waits for 10 seconds and makes sure we timeout 
Example #7
Source File: test_downloader.py    From gallery-dl with GNU General Public License v2.0 5 votes vote down vote up
def setUpClass(cls):
        TestDownloaderBase.setUpClass()
        cls.downloader = downloader.find("http")(cls.job)

        port = 8088
        cls.address = "http://127.0.0.1:{}".format(port)
        cls._jpg = cls.address + "/image.jpg"
        cls._png = cls.address + "/image.png"
        cls._gif = cls.address + "/image.gif"

        server = http.server.HTTPServer(("", port), HttpRequestHandler)
        threading.Thread(target=server.serve_forever, daemon=True).start() 
Example #8
Source File: __main__.py    From oslo.middleware with Apache License 2.0 5 votes vote down vote up
def main(args=None):
    """Runs a basic http server to show healthcheck functionality."""
    parser = argparse.ArgumentParser()
    parser.add_argument("-p", "--port",
                        help="Unused port to run the tiny"
                             " http server on (or zero to select a"
                             " random unused port)",
                        type=positive_int, required=True)
    args = parser.parse_args(args=args)
    server = create_server(args.port)
    print("Serving at port: %s" % server.server_address[1])
    server.serve_forever() 
Example #9
Source File: plugin_listener.py    From deen with Apache License 2.0 5 votes vote down vote up
def _http_python3(self, listen_ssl=False):
        """Listen for HTTP connections with Python 3."""
        handler = DeenHTTPRequestHandler
        os.chdir(self.serving_directory)
        try:
            with socketserver.TCPServer(self.listen_socket, handler) as httpd:
                if listen_ssl:
                    # The certificate chain and private key need to
                    # be available as actual files that can be opened
                    # with fopen(3).
                    with tempfile.TemporaryDirectory() as tmpdirname:
                        cert_chain = tmpdirname + '/cert_chain.pem'
                        server_key = tmpdirname + '/server_key.pem'
                        with open(cert_chain, 'wb') as f:
                            f.write(self.server_cert_pem)
                        with open(server_key, 'wb') as f:
                            f.write(self.server_key_pem)
                        httpd.socket = ssl.wrap_socket(httpd.socket,
                                                       certfile=cert_chain,
                                                       keyfile=server_key,
                                                       server_side=True)
                message = 'Serving HTTP at port ' + str(self.listen_port)
                if listen_ssl:
                    message += ' (SSL)'
                print(message)
                try:
                    httpd.serve_forever()
                except KeyboardInterrupt:
                    httpd.socket.close()
        except OSError as e:
            self.error = e
            self.log.error(self.error)
            self.log.debug(self.error, exc_info=True) 
Example #10
Source File: poodle.py    From POODLEAttack with GNU General Public License v2.0 5 votes vote down vote up
def ssltlsServer(victims, poodleManager):
    print("Starting SSL/TLS server on {}:{} forwarding to {}:{}".format(args.listen_host, args.listen_port_tls, args.target_host, args.target_port))
    server = SSLTLSProxy((args.listen_host, int(args.listen_port_tls)), SSLTLSHandler)
    server.victims = victims
    server.poodleManager = poodleManager
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("Shutdown of SSL/TLS server on user request") 
Example #11
Source File: poodle.py    From POODLEAttack with GNU General Public License v2.0 5 votes vote down vote up
def httpServer(victims, poodleManager):
    print("Starting HTTP server on {}:{} generating requests to {}".format(args.listen_host, args.listen_port_http, args.targetURL))
    server = http.server.HTTPServer((args.listen_host, int(args.listen_port_http)), PoodleHTTPRequestHandler)
    server.victims = victims
    server.poodleManager = poodleManager
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("Shutdown of HTTP server on user request") 
Example #12
Source File: test_utils.py    From hub with Apache License 2.0 4 votes vote down vote up
def start_smart_module_server(download_url):
  """Serve documentation and module requests at the same URL."""
  # pylint:disable=g-import-not-at-top
  if sys.version_info[0] == 2:
    import BaseHTTPServer
    import SimpleHTTPServer
    import urlparse

    class HTTPServerV6(BaseHTTPServer.HTTPServer):

      address_family = socket.AF_INET6

    class RequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):

      def do_GET(self):
        parsed_url = urlparse.urlparse(self.path)
        qs = urlparse.parse_qs(parsed_url.query)
        if qs["tf-hub-format"][0] == "compressed":
          _do_redirect(self, download_url)
        else:
          _do_documentation(self)

    server = HTTPServerV6(("", 0), RequestHandler)
    server_port = server.server_port
  else:
    import http.server
    import socketserver
    import urllib

    class TCPServerV6(socketserver.TCPServer):

      address_family = socket.AF_INET6

    class RequestHandler(http.server.SimpleHTTPRequestHandler):

      def do_GET(self):
        parsed_url = urllib.parse.urlparse(self.path)
        qs = urllib.parse.parse_qs(parsed_url.query)
        if qs["tf-hub-format"][0] == "compressed":
          _do_redirect(self, download_url)
        else:
          _do_documentation(self)

    server = TCPServerV6(("", 0), RequestHandler)
    _, server_port, _, _ = server.server_address
  # pylint:disable=g-import-not-at-top

  thread = threading.Thread(target=server.serve_forever)
  thread.daemon = True
  thread.start()

  return server_port 
Example #13
Source File: test_utils.py    From hub with Apache License 2.0 4 votes vote down vote up
def start_http_server(redirect=None):
  """Returns the port of the newly started HTTP server."""

  # Start HTTP server to serve TAR files.
  # pylint:disable=g-import-not-at-top
  if sys.version_info[0] == 2:
    import BaseHTTPServer
    import SimpleHTTPServer

    class HTTPServerV6(BaseHTTPServer.HTTPServer):

      address_family = socket.AF_INET6

    class RedirectHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):

      def do_GET(self):
        _do_redirect(self, redirect)

    server = HTTPServerV6(("", 0), RedirectHandler if redirect else
                          SimpleHTTPServer.SimpleHTTPRequestHandler)
    server_port = server.server_port
  else:
    import http.server
    import socketserver

    class TCPServerV6(socketserver.TCPServer):

      address_family = socket.AF_INET6

    class RedirectHandler(http.server.SimpleHTTPRequestHandler):

      def do_GET(self):
        _do_redirect(self, redirect)

    server = TCPServerV6(("", 0), RedirectHandler if redirect else
                         http.server.SimpleHTTPRequestHandler)
    _, server_port, _, _ = server.server_address
  # pylint:disable=g-import-not-at-top

  thread = threading.Thread(target=server.serve_forever)
  thread.daemon = True
  thread.start()

  return server_port