Python http.server.BaseHTTPRequestHandler() Examples
The following are 30
code examples of http.server.BaseHTTPRequestHandler().
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: 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 #2
Source File: modules.py From cjworkbench with GNU Affero General Public License v3.0 | 7 votes |
def _get_singleton_http_server() -> HTTPServer: class Handler(BaseHTTPRequestHandler): def do_GET(self): try: entry = ZIPFILE_ENTRIES[self.path] except KeyError: self.send_error(404) return self.send_response(200) self.send_header("Content-Type", "application/zip") self.end_headers() self.wfile.write(entry.body) server = HTTPServer(("module-zipfile-server", 0), Handler) thread = threading.Thread( target=server.serve_forever, kwargs={"poll_interval": 0.005} ) thread.setDaemon(True) # so it dies when we finish integration-testing thread.start() return server
Example #3
Source File: server.py From altair with BSD 3-Clause "New" or "Revised" License | 7 votes |
def generate_handler(html, files=None): if files is None: files = {} class MyHandler(server.BaseHTTPRequestHandler): def do_GET(self): """Respond to a GET request.""" if self.path == "/": self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(html.encode()) elif self.path in files: content_type, content = files[self.path] self.send_response(200) self.send_header("Content-type", content_type) self.end_headers() self.wfile.write(content.encode()) else: self.send_error(404) return MyHandler
Example #4
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 #5
Source File: progress_server.py From cozy with Apache License 2.0 | 7 votes |
def handler_class(callback): class Handler(BaseHTTPRequestHandler): def do_GET(self): if self.path != "/": self.send_response(404) content = "not found" self.send_header("Content-Type", "text/plain") self.send_header("Content-Length", str(len(content))) self.end_headers() self.wfile.write(content.encode("utf-8")) return content = callback() self.send_response(200) self.send_header("Content-Type", "text/html") self.send_header("Content-Length", str(len(content))) self.end_headers() self.wfile.write(content.encode("ascii")) return Handler
Example #6
Source File: test_logging.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 7 votes |
def __init__(self, addr, handler, poll_interval=0.5, log=False, sslctx=None): class DelegatingHTTPRequestHandler(BaseHTTPRequestHandler): def __getattr__(self, name, default=None): if name.startswith('do_'): return self.process_request raise AttributeError(name) def process_request(self): self.server._handler(self) def log_message(self, format, *args): if log: super(DelegatingHTTPRequestHandler, self).log_message(format, *args) HTTPServer.__init__(self, addr, DelegatingHTTPRequestHandler) ControlMixin.__init__(self, handler, poll_interval) self.sslctx = sslctx
Example #7
Source File: listener_server.py From PerfKitBenchmarker with Apache License 2.0 | 7 votes |
def __init__(self, pool, launcher, queue, access_port, *args, **kwargs): """Creates a RequestHandler for a http request received by the server. Args: pool: multiprocessing process pool object. launcher: name string of the launcher vm that the server is on. queue: multiprocessing queue object. access_port: port number to call on the booted vms. *args: Other argments to apply to the request handler. **kwargs: Keyword arguments to apply to the request handler. """ self.process_pool = pool self.launcher = launcher self.timing_queue = queue self.access_port = access_port # BaseHTTPRequestHandler calls do_GET inside __init__ # So we have to call super().__init__ after setting attributes. super(RequestHandler, self).__init__(*args, **kwargs)
Example #8
Source File: test_stardog.py From integrations-extras with BSD 3-Clause "New" or "Revised" License | 7 votes |
def __init__(self): super(HttpServerThread, self).__init__() self.done = False self.hostname = 'localhost' class MockStardog(BaseHTTPRequestHandler): def do_GET(self): if self.path != '/admin/status': self.send_response(404) return self.send_response(200) self.send_header('Content-type', 'application/json') self.end_headers() # json.dumps always outputs a str, wfile.write requires bytes self.wfile.write(ensure_bytes(json.dumps(DATA))) self.http = HTTPServer((self.hostname, 0), MockStardog) self.port = self.http.server_port
Example #9
Source File: test_logging.py From ironpython3 with Apache License 2.0 | 7 votes |
def __init__(self, addr, handler, poll_interval=0.5, log=False, sslctx=None): class DelegatingHTTPRequestHandler(BaseHTTPRequestHandler): def __getattr__(self, name, default=None): if name.startswith('do_'): return self.process_request raise AttributeError(name) def process_request(self): self.server._handler(self) def log_message(self, format, *args): if log: super(DelegatingHTTPRequestHandler, self).log_message(format, *args) HTTPServer.__init__(self, addr, DelegatingHTTPRequestHandler) ControlMixin.__init__(self, handler, poll_interval) self.sslctx = sslctx
Example #10
Source File: test_auth.py From flytekit with Apache License 2.0 | 6 votes |
def test_oauth_http_server(): queue = _Queue() server = _auth.OAuthHTTPServer(("localhost", 9000), _BaseHTTPServer.BaseHTTPRequestHandler, queue=queue) test_auth_code = "auth_code" server.handle_authorization_code(test_auth_code) auth_code = queue.get() assert test_auth_code == auth_code
Example #11
Source File: test_googlesheets.py From cjworkbench with GNU Affero General Public License v3.0 | 6 votes |
def setUp(self): super().setUp() self.last_http_requestline = None self.mock_http_response = None class Handler(BaseHTTPRequestHandler): def do_GET(self2): self.last_http_requestline = self2.requestline r = self.mock_http_response if r is None: raise RuntimeError("Tests must overwrite self.mock_http_response") self2.send_response_only(r.status_code) for header, value in r.headers: self2.send_header(header, value) self2.end_headers() self2.wfile.write(r.body) self.server = HTTPServer(("localhost", 0), Handler) self.server.socket = self.ssl_server_ctx.wrap_socket( self.server.socket, server_side=True ) self.server_thread = threading.Thread( target=self.server.serve_forever, kwargs={"poll_interval": 0.005} ) self.server_thread.setDaemon(True) self.server_thread.start() self.old_ssl_context = googlesheets.SSL_CONTEXT self.old_api_url = googlesheets.GDRIVE_API_URL googlesheets.GDRIVE_API_URL = ( f"https://{self.server.server_address[0]}:{self.server.server_address[1]}" ) googlesheets.SSL_CONTEXT = self.ssl_client_ctx
Example #12
Source File: test_loadurl.py From cjworkbench with GNU Affero General Public License v3.0 | 6 votes |
def setUp(self): super().setUp() self.http_requestlines = [] self.mock_http_response = None class Handler(BaseHTTPRequestHandler): def do_GET(self2): self.http_requestlines.append(self2.requestline) r = self.mock_http_response if hasattr(r, "__next__"): r = next(r) if r is None: raise RuntimeError("Tests must overwrite self.mock_http_response") self2.send_response_only(r.status_code) for header, value in r.headers: self2.send_header(header, value) self2.end_headers() write = self2.wfile.write if isinstance(r.body, list): # chunked encoding for chunk in r.body: write(("%x\r\n" % len(chunk)).encode("ascii")) write(chunk) write(b"\r\n") write(b"0\r\n\r\n") else: # just write the bytes write(r.body) self.server = HTTPServer(("127.0.0.1", 0), Handler) self.server_thread = threading.Thread( target=self.server.serve_forever, kwargs={"poll_interval": 0.005} ) self.server_thread.setDaemon(True) self.server_thread.start()
Example #13
Source File: probe_endtoend.py From telepresence with Apache License 2.0 | 6 votes |
def run_http_server(port, value): class SingleValueHTTPRequestHandler(BaseHTTPRequestHandler): def do_GET(self): response_body = value.encode("utf-8") self.send_response(200) self.send_header("Content-Type", "text/plain") self.send_header("Content-Length", str(len(response_body))) self.end_headers() self.wfile.write(response_body) server = HTTPServer(("", port), SingleValueHTTPRequestHandler) Thread(target=server.serve_forever, daemon=True).start()
Example #14
Source File: main.py From tuna with GNU General Public License v3.0 | 6 votes |
def start_server(prof_filename, start_browser, port): data = read(prof_filename) class StaticServer(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) if self.path == "/": self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(render(data, prof_filename).encode("utf-8")) else: this_dir = Path(__file__).resolve().parent filepath = this_dir / "web" / self.path[1:] mimetype, _ = mimetypes.guess_type(str(filepath)) self.send_header("Content-type", mimetype) self.end_headers() with open(filepath, "rb") as fh: content = fh.read() self.wfile.write(content) return if port is None: port = 8000 while is_port_in_use(port): port += 1 httpd = HTTPServer(("", port), StaticServer) if start_browser: address = f"http://localhost:{port}" threading.Thread(target=lambda: webbrowser.open_new_tab(address)).start() print(f"Starting httpd on port {port}") httpd.serve_forever()
Example #15
Source File: stream2chromecast.py From stream2chromecast with GNU General Public License v3.0 | 6 votes |
def handle_one_request(self): try: return BaseHTTPServer.BaseHTTPRequestHandler.handle_one_request(self) except socket.error: if not self.suppress_socket_error_report: raise
Example #16
Source File: python_test_server.py From dcos with Apache License 2.0 | 6 votes |
def log_message(self, fmt, *args): """Override logging settings of base class This method reformats standard request logging provided by the base class BaseHTTPRequestHandler and sends it to logger/formatter configured by the user during logging module initialization Args: fmt, args: just like base class """ logging.info("REQ: {0} {1}".format(self.address_string(), fmt % args))
Example #17
Source File: test_logging.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
def __init__(self, addr, handler, poll_interval=0.5, log=False, sslctx=None): class DelegatingHTTPRequestHandler(BaseHTTPRequestHandler): def __getattr__(self, name, default=None): if name.startswith('do_'): return self.process_request raise AttributeError(name) def process_request(self): self.server._handler(self) def log_message(self, format, *args): if log: super(DelegatingHTTPRequestHandler, self).log_message(format, *args) HTTPServer.__init__(self, addr, DelegatingHTTPRequestHandler) ControlMixin.__init__(self, handler, poll_interval) self.sslctx = sslctx
Example #18
Source File: test_mypy_http_request_handler.py From mypy-tools with MIT License | 6 votes |
def __init__(self, ip_port, handler_cls, file_cache, path): # type: (Tuple[str, int], Type[BaseHTTPRequestHandler], Any, str) -> None self.file_cache = file_cache self.active_request = MockRequest(path) handler = handler_cls(self.active_request, ip_port, self) # type: ignore
Example #19
Source File: testing.py From pydu with MIT License | 6 votes |
def __init__(self, RequestHandler=BaseHTTPRequestHandler): self.RequestHandler = RequestHandler self.server = None self.port = None
Example #20
Source File: oauth2.py From python-eduvpn-client with GNU General Public License v3.0 | 6 votes |
def one_request(port, lets_connect, timeout=None): # type: (int, bool, Optional[int]) -> str """ Listen for one http request on port, then close and return request query args: port (int): the port to listen for the request returns: str: the request """ logger.info(u"listening for a request on port {}...".format(port)) class RequestHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() logo, name = get_brand(lets_connect) logo = stringify_image(logo) content = landing_page.format(logo=logo, brand=name).encode('utf-8') self.wfile.write(content) self.server.path = self.path httpd = HTTPServer(('', port), RequestHandler) if timeout: httpd.socket.settimeout(timeout) httpd.handle_request() httpd.server_close() if not hasattr(httpd, "path"): raise Exception("Invalid response received") parsed = urlparse(httpd.path) # type: ignore logger.info(u"received a request {}".format(httpd.path)) # type: ignore return parse_qs(parsed.query)
Example #21
Source File: test_pool.py From kuryr-kubernetes with Apache License 2.0 | 6 votes |
def setUp(self): super(TestRequestHandler, self).setUp() client_address = 'localhost' server = '/tmp/server.lock' req = mock.MagicMock() with mock.patch.object(BaseHTTPRequestHandler, '__init__') as m_http: m_http.return_value = None self._req_handler = m_pool.RequestHandler(req, client_address, server) self._req_handler.rfile = mock.Mock() self._req_handler.wfile = mock.Mock()
Example #22
Source File: stream2chromecast.py From stream2chromecast with GNU General Public License v3.0 | 5 votes |
def finish(self): try: return BaseHTTPServer.BaseHTTPRequestHandler.finish(self) except socket.error: if not self.suppress_socket_error_report: raise
Example #23
Source File: connection.py From agents-aea with Apache License 2.0 | 5 votes |
def create(cls, request_handler: BaseHTTPRequestHandler) -> "Request": """ Create a request. :param request_handler: the request handler :return: a request """ method = request_handler.command.lower() parsed_path = urlparse(request_handler.path) url = "http://{}:{}{}".format( *request_handler.server.server_address, parsed_path.path ) content_length = request_handler.headers["Content-Length"] body = ( None if content_length is None else request_handler.rfile.read(int(content_length)).decode() ) mimetype = request_handler.headers.get_content_type() query_params = parse_qs(parsed_path.query, keep_blank_values=True) parameters = RequestParameters( query=ImmutableMultiDict(query_params), header=request_handler.headers.as_string(), path={}, ) request = Request( full_url_pattern=url, method=method, parameters=parameters, body=body, mimetype=mimetype, ) request.id = uuid4().hex return request
Example #24
Source File: test_wof_http.py From tilequeue with MIT License | 5 votes |
def __init__(self, context, *args): self.wof_ctx = context http.BaseHTTPRequestHandler.__init__(self, *args)
Example #25
Source File: test_bigquery_proxy.py From docker-python with Apache License 2.0 | 5 votes |
def _test_proxy(self, client): class HTTPHandler(BaseHTTPRequestHandler): called = False proxy_header_found = False def do_HEAD(self): self.send_response(200) def do_GET(self): HTTPHandler.called = True HTTPHandler.proxy_header_found = any( k for k in self.headers if k == "X-KAGGLE-PROXY-DATA" and self.headers[k] == "test-key") 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(os.getenv('KAGGLE_DATA_PROXY_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.proxy_header_found, msg="X-KAGGLE-PROXY-DATA header was missing from the BQ proxy request.")
Example #26
Source File: PServer.py From SCope with GNU General Public License v3.0 | 5 votes |
def handle(self): "Lets parent object handle, but redirects socket exceptions as 'Abort's." try: httpserver.BaseHTTPRequestHandler.handle(self) except socket.error as e: logger.error(str(e)) raise Abort(str(e))
Example #27
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
Example #28
Source File: sparrowwifiagent.py From sparrow-wifi with GNU General Public License v3.0 | 5 votes |
def log_message(self, format, *args): global debugHTTP if not debugHTTP: return else: HTTPServer.BaseHTTPRequestHandler(format, *args)
Example #29
Source File: webbrowser_authenticate.py From inference-model-manager with Apache License 2.0 | 5 votes |
def run_server(port, auth_url): class Server(BaseHTTPRequestHandler): def log_message(self, format, *args): return def _set_headers(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() def do_GET(self): self._set_headers() query = urlparse(self.path).query parsed_query = parse_qs(query) if 'code' in parsed_query: print("A request was received with an authorization code.") global code code = parsed_query['code'][0] self.prepare_response() self.kill_server() def prepare_response(self): python_ver = sys.version_info.major if python_ver == 3: self.wfile.write(bytes(html_page, 'UTF-8')) else: self.wfile.write(html_page) def kill_server(self): assassin = threading.Thread(target=httpd.shutdown) assassin.daemon = True assassin.start() handler_class = Server server_address = ('', port) httpd = HTTPServer(server_address, handler_class) open_webbrowser(auth_url) print('Waiting for authorization code.') httpd.serve_forever()
Example #30
Source File: test_exposition.py From client_python with Apache License 2.0 | 5 votes |
def setUp(self): self.registry = CollectorRegistry() self.counter = Gauge('g', 'help', registry=self.registry) self.requests = requests = [] class TestHandler(BaseHTTPRequestHandler): def do_PUT(self): if 'with_basic_auth' in self.requestline and self.headers['authorization'] != 'Basic Zm9vOmJhcg==': self.send_response(401) else: self.send_response(201) length = int(self.headers['content-length']) requests.append((self, self.rfile.read(length))) self.end_headers() do_POST = do_PUT do_DELETE = do_PUT httpd = HTTPServer(('localhost', 0), TestHandler) self.address = 'http://localhost:{0}'.format(httpd.server_address[1]) class TestServer(threading.Thread): def run(self): httpd.handle_request() self.server = TestServer() self.server.daemon = True self.server.start()