Python http.server.HTTPServer() Examples
The following are 30
code examples of http.server.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
http.server
, or try the search function
.
![](https://www.programcreek.com/common/static/images/search.png)
Example #1
Source File: conftest.py From vue.py with MIT License | 11 votes |
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: test_bigquery.py From docker-python with Apache License 2.0 | 8 votes |
def _test_integration(self, client): class HTTPHandler(BaseHTTPRequestHandler): called = False bearer_header_found = False def do_HEAD(self): self.send_response(200) def do_GET(self): HTTPHandler.called = True HTTPHandler.bearer_header_found = any( k for k in self.headers if k == "authorization" and self.headers[k] == "Bearer secret") self.send_response(200) self.send_header("Content-type", "application/json") self.end_headers() sample_dataset = { "id": "bigqueryproject:datasetname", "datasetReference": { "datasetId": "datasetname", "projectId": "bigqueryproject" } } self.wfile.write(json.dumps({"kind": "bigquery#datasetList", "datasets": [sample_dataset]}).encode("utf-8")) server_address = urlparse(self.API_BASE_URL) with HTTPServer((server_address.hostname, server_address.port), HTTPHandler) as httpd: threading.Thread(target=httpd.serve_forever).start() for dataset in client.list_datasets(): self.assertEqual(dataset.dataset_id, "datasetname") httpd.shutdown() self.assertTrue( HTTPHandler.called, msg="Fake server was not called from the BQ client, but should have been.") self.assertTrue( HTTPHandler.bearer_header_found, msg="authorization header was missing from the BQ request.")
Example #3
Source File: topola_server.py From addons-source with GNU General Public License v2.0 | 7 votes |
def run(self): server = self class Handler(BaseHTTPRequestHandler): def do_GET(self): """Serves the GEDCOM file and referenced files.""" # Take the file map in a thread-safe way. with server.lock: file_map = server.file_map # Return 404 if a file is not known. if not self.path in file_map: self.send_response(404) return # Respond with the file contents. self.send_response(200) self.send_header('Access-Control-Allow-Origin', 'https://pewu.github.io') self.end_headers() content = open(file_map[self.path], 'rb').read() self.wfile.write(content) # Bind to the local address only. server_address = ('127.0.0.1', self.port) httpd = HTTPServer(server_address, Handler) httpd.serve_forever()
Example #4
Source File: communication.py From pyDcop with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _start_server(self): # start a server listening for messages self.logger.info( "Starting http server for HttpCommunicationLayer " "on %s", self.address ) try: _, port = self._address self.httpd = HTTPServer(("0.0.0.0", port), MPCHttpHandler) except OSError: self.logger.error( "Cannot bind http server on adress {}".format(self.address) ) raise self.httpd.comm = self t = Thread(name="http_thread", target=self.httpd.serve_forever, daemon=True) t.start()
Example #5
Source File: itn_helpers.py From django-payfast with MIT License | 6 votes |
def itn_handler(host, port): # type: (str, int) -> Iterator[Queue] """ Usage:: with itn_handler(ITN_HOST, ITN_PORT) as itn_queue: # ...complete PayFast payment... itn_data = itn_queue.get(timeout=2) """ server_address = (host, port) http_server = HTTPServer(server_address, PayFastITNHandler) http_server.itn_queue = Queue() # type: ignore executor = ThreadPoolExecutor(max_workers=1) executor.submit(http_server.serve_forever) try: yield http_server.itn_queue # type: ignore finally: http_server.shutdown()
Example #6
Source File: docs.py From fastapi with MIT License | 6 votes |
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 #7
Source File: http_server.py From avocado-vt with GNU General Public License v2.0 | 6 votes |
def http_server(port=8000, cwd=None, terminate_callable=None): http = HTTPServer(('', port), HTTPRequestHandler) http.timeout = 1 if cwd is None: cwd = os.getcwd() http.cwd = cwd while True: if terminate_callable is not None: terminate = terminate_callable() else: terminate = False if terminate: break http.handle_request()
Example #8
Source File: exports.py From django-prometheus with Apache License 2.0 | 6 votes |
def SetupPrometheusEndpointOnPort(port, addr=""): """Exports Prometheus metrics on an HTTPServer running in its own thread. The server runs on the given port and is by default listenning on all interfaces. This HTTPServer is fully independent of Django and its stack. This offers the advantage that even if Django becomes unable to respond, the HTTPServer will continue to function and export metrics. However, this also means that the features offered by Django (like middlewares or WSGI) can't be used. Now here's the really weird part. When Django runs with the auto-reloader enabled (which is the default, you can disable it with `manage.py runserver --noreload`), it forks and executes manage.py twice. That's wasteful but usually OK. It starts being a problem when you try to open a port, like we do. We can detect that we're running under an autoreloader through the presence of the RUN_MAIN environment variable, so we abort if we're trying to export under an autoreloader and trying to open a port. """ assert os.environ.get("RUN_MAIN") != "true", ( "The thread-based exporter can't be safely used when django's " "autoreloader is active. Use the URL exporter, or start django " "with --noreload. See documentation/exports.md." ) prometheus_client.start_http_server(port, addr=addr)
Example #9
Source File: interactive_web.py From ParlAI with MIT License | 6 votes |
def interactive_web(opt, parser): SHARED['opt'] = parser.opt SHARED['opt']['task'] = 'parlai.agents.local_human.local_human:LocalHumanAgent' # Create model and assign it to the specified task agent = create_agent(SHARED.get('opt'), requireModelExists=True) SHARED['agent'] = agent SHARED['world'] = create_task(SHARED.get('opt'), SHARED['agent']) # show args after loading model parser.opt = agent.opt parser.print_args() MyHandler.protocol_version = 'HTTP/1.0' httpd = HTTPServer((opt['host'], opt['port']), MyHandler) logging.info('http://{}:{}/'.format(opt['host'], opt['port'])) try: httpd.serve_forever() except KeyboardInterrupt: pass httpd.server_close()
Example #10
Source File: sso_token_receiver.py From Moodle-Downloader-2 with GNU General Public License v3.0 | 6 votes |
def receive_token() -> str: """ Starts an HTTP server to receive the SSO token from browser. It waits till a token was received. """ server_address = ('localhost', 80) try: httpd = HTTPServer(server_address, TransferServer) except PermissionError: Log.error('Permission denied: Please start the' + ' downloader once with administrator rights, so that it' + ' can wait on port 80 for the token.') exit(1) extracted_token = None while extracted_token is None: httpd.handle_request() extracted_token = extract_token(TransferServer.received_token) httpd.server_close() return extracted_token
Example #11
Source File: server.py From sparrest with MIT License | 6 votes |
def run_on(ip, port): """ Starts the HTTP server in the given port :param port: port to run the http server :return: void """ print("Starting a server on port {0}. Use CNTRL+C to stop the server.".format(port)) server_address = (ip, port) try: httpd = HTTPServer(server_address, SparrestHandler) httpd.serve_forever() except OSError as e: if e.errno == 48: # port already in use print("ERROR: The port {0} is already used by another process.".format(port)) else: raise OSError except KeyboardInterrupt as interrupt: print("Server stopped. Bye bye!")
Example #12
Source File: logdnaHandlerTest.py From python with MIT License | 5 votes |
def stops_retention_when_buf_is_full(self): options = { 'hostname': 'localhost', 'url': 'http://localhost:1337', 'ip': '10.0.1.1', 'mac': 'C0:FF:EE:C0:FF:EE', 'buf_retention_limit': 50, 'equest_timeout': 10, 'flush_interval': 1, 'retry_interval_secs': 1 } server_address = ('localhost', 1337) httpd = HTTPServer(server_address, failed_RequestHandler) failed_case_logger = LogDNAHandler(key, options) log.addHandler(failed_case_logger) line = "when buffer grows bigger than we want" lineTwo = "when buffer grows bigger than we want. And more and more" def send_log_to_fail(): log.info(line) log.info(lineTwo) server_thread = threading.Thread(target=httpd.handle_request) logdna_thread = threading.Thread(target=send_log_to_fail) server_thread.daemon = True logdna_thread.daemon = True server_thread.start() logdna_thread.start() server_thread.join() logdna_thread.join() self.assertEqual(len(failed_case_logger.buf), 1) self.assertNotEqual(failed_case_logger.buf[0]['line'], lineTwo)
Example #13
Source File: listener.py From logzio-python-handler with Apache License 2.0 | 5 votes |
def __init__(self): self.port = _find_available_port() self.host = "localhost" self.server = HTTPServer((self.host, self.port), ListenerHandler) self.listening_thread = Thread(target=self._start_listening) self.listening_thread.daemon = True self.listening_thread.name = "mock-logzio-listener" self.listening_thread.start() self.logs_list = logs_list.list self.persistent_flags = persistent_flags
Example #14
Source File: test_robotparser.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def setUp(self): self.server = HTTPServer((support.HOST, 0), RobotHandler) self.t = threading.Thread( name='HTTPServer serving', target=self.server.serve_forever, # Short poll interval to make the test finish quickly. # Time between requests is short enough that we won't wake # up spuriously too many times. kwargs={'poll_interval':0.01}) self.t.daemon = True # In case this function raises. self.t.start()
Example #15
Source File: keylime_agent.py From keylime with BSD 2-Clause "Simplified" License | 5 votes |
def __init__(self, server_address, RequestHandlerClass, agent_uuid): """Constructor overridden to provide ability to pass configuration arguments to the server""" secdir = secure_mount.mount() keyname = "%s/%s"%(secdir,config.get('cloud_agent','rsa_keyname')) # read or generate the key depending on configuration if os.path.isfile(keyname): # read in private key logger.debug( "Using existing key in %s"%keyname) f = open(keyname,"rb") rsa_key = crypto.rsa_import_privkey(f.read()) else: logger.debug("key not found, generating a new one") rsa_key = crypto.rsa_generate(2048) with open(keyname,"wb") as f: f.write(crypto.rsa_export_privkey(rsa_key)) self.rsaprivatekey = rsa_key self.rsapublickey_exportable = crypto.rsa_export_pubkey(self.rsaprivatekey) #attempt to get a U value from the TPM NVRAM nvram_u = tpm.read_key_nvram() if nvram_u is not None: logger.info("Existing U loaded from TPM NVRAM") self.add_U(nvram_u) http.server.HTTPServer.__init__(self, server_address, RequestHandlerClass) self.enc_keyname = config.get('cloud_agent','enc_keyname') self.agent_uuid = agent_uuid
Example #16
Source File: registrar_common.py From keylime with BSD 2-Clause "Simplified" License | 5 votes |
def shutdown(self): http.server.HTTPServer.shutdown(self)
Example #17
Source File: registrar_common.py From keylime with BSD 2-Clause "Simplified" License | 5 votes |
def __init__(self, server_address, RequestHandlerClass): """Constructor overridden to provide ability to read file""" http.server.HTTPServer.__init__( self, server_address, RequestHandlerClass)
Example #18
Source File: 1_myhttpd.py From deep-learning-note with MIT License | 5 votes |
def main(): try: server = HTTPServer(('', 80), MyHandler) print('Welcome to the machine...') print('Press ^C once or twice to quit.') server.serve_forever() except KeyboardInterrupt: print('^C received, shutting down server') server.socket.close()
Example #19
Source File: registrar_common.py From keylime with BSD 2-Clause "Simplified" License | 5 votes |
def shutdown(self): http.server.HTTPServer.shutdown(self)
Example #20
Source File: registrar_common.py From keylime with BSD 2-Clause "Simplified" License | 5 votes |
def __init__(self, server_address, RequestHandlerClass): """Constructor overridden to provide ability to read file""" http.server.HTTPServer.__init__( self, server_address, RequestHandlerClass)
Example #21
Source File: test_nmapconnector.py From grinder with GNU General Public License v2.0 | 5 votes |
def teardown_module() -> None: """ Stop HTTPServer :return: """ server_v4.shutdown() server_v6.shutdown()
Example #22
Source File: test_nmapconnector.py From grinder with GNU General Public License v2.0 | 5 votes |
def setup_module() -> None: """ Initialize HTTPServer for test NmapConnector scanning and NmapConnector for various tests :return: """ global server_v4 server_v4 = HTTPServer( (NmapTestDefaultValues.HOST4, NmapTestDefaultValues.PORT4), SimpleHTTPRequestHandler, ) s_v4 = Thread(target=server_v4.serve_forever, daemon=True) s_v4.start() global server_v6 server_v6 = HTTPServer6( (NmapTestDefaultValues.HOST6, NmapTestDefaultValues.PORT6), SimpleHTTPRequestHandler, ) s_v6 = Thread(target=server_v6.serve_forever, daemon=True) s_v6.start() global nm nm = NmapConnector() global empty_nm empty_nm = NmapConnector() global nm_v4 nm_v4 = NmapConnector() global nm_v6 nm_v6 = NmapConnector()
Example #23
Source File: dummy_http_server.py From outreachy with BSD 3-Clause "New" or "Revised" License | 5 votes |
def run(port = 80): dummy_server = HTTPServer(("localhost", port), DummyServer) print('Starting dummy server...') try: dummy_server.serve_forever() except KeyboardInterrupt: pass dummy_server.server_close()
Example #24
Source File: test_integration.py From brotab with MIT License | 5 votes |
def run(self, host=ECHO_SERVER_HOST, port=ECHO_SERVER_PORT): self._server = HTTPServer((host, port), EchoRequestHandler) self._thread = threading.Thread( target=self._server.serve_forever, daemon=True) self._thread.start()
Example #25
Source File: mock_imanage_server.py From lexpredict-contraxsuite with GNU Affero General Public License v3.0 | 5 votes |
def start(cls): cls.mock_server_port = 65534 # get_free_port() cls.mock_server = HTTPServer(('localhost', cls.mock_server_port), MockServerRequestHandler) cls.mock_server_thread = Thread(target=cls.mock_server.serve_forever) cls.mock_server_thread.setDaemon(False) cls.mock_server_thread.start() print('Started mock iManage server at localhost:' + str(cls.mock_server_port))
Example #26
Source File: splunk_whisperer.py From splunk_whisperer with MIT License | 5 votes |
def start_fake_deployment_server(port): server_address = ('', port) httpd = HTTPServer(('',port), FakeDeploymentServerHandler) # openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 httpd.socket = ssl.wrap_socket(httpd.socket, server_side=True, certfile=CERT_FILE) th = threading.Thread(target=httpd.serve_forever) th.daemon = True th.start() return httpd
Example #27
Source File: reprocess_screenshots.py From IkaLog with Apache License 2.0 | 5 votes |
def _run_server(args): print(args) httpd = HTTPServer((args.bind_addr, args.bind_port), HTTPRequestHandler) # httpd._scoreboard_recognition.apply_arguments(args) print('serving at port', args.bind_port) httpd.serve_forever() # Extract battle_id from stat.ink screenshot filename.
Example #28
Source File: cli.py From lambda-proxy with BSD 2-Clause "Simplified" License | 5 votes |
def run(port): """Launch server.""" server_address = ("", port) httpd = HTTPServer(server_address, HTTPRequestHandler) click.echo(f"Starting local server at http://127.0.0.1:{port}", err=True) httpd.serve_forever()
Example #29
Source File: test_reorg_detector.py From django-eth-events with MIT License | 5 votes |
def start_mock_server(): server_address = ('127.0.0.1', 8545) httpd = HTTPServer(server_address, MockedTestrpc) httpd.serve_forever() print('served internal')
Example #30
Source File: utils.py From searchlight with Apache License 2.0 | 5 votes |
def start_http_server(image_id, image_data): def _get_http_handler_class(fixture): class StaticHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('Content-Length', str(len(fixture))) self.end_headers() self.wfile.write(fixture) return def do_HEAD(self): self.send_response(200) self.send_header('Content-Length', str(len(fixture))) self.end_headers() return def log_message(self, *args, **kwargs): # Override this method to prevent debug output from going # to stderr during testing return return StaticHTTPRequestHandler server_address = ('127.0.0.1', 0) handler_class = _get_http_handler_class(image_data) httpd = BaseHTTPServer.HTTPServer(server_address, handler_class) port = httpd.socket.getsockname()[1] pid = os.fork() if pid == 0: httpd.serve_forever() else: return pid, port