def test_staff_control(self): "Test the staff control view" class NoLogHandler(SimpleHTTPRequestHandler): def log_message(self, format, *args): return server = HTTPServer(("localhost", 8898), NoLogHandler) mock_server_thread = Thread(target=server.serve_forever) mock_server_thread.setDaemon(True) mock_server_thread.start() login(self, 'admin') post_context = {'action': "initial"} response = self.client.post(reverse('control'), post_context) self.assertEqual(response.status_code, 302) post_context = {'action': "reset"} response = self.client.post(reverse('control'), post_context) self.assertEqual(response.status_code, 302) # post_context = {'action': "getpuzzles", "hunt_number": "1"} # response = self.client.post(reverse('control'), post_context) # self.assertEqual(response.status_code, 200) # post_context = {'action': "getpuzzles", "puzzle_number": "1", "puzzle_id": "201"} # response = self.client.post(reverse('control'), post_context) # self.assertEqual(response.status_code, 200) post_context = {'action': "new_current_hunt", "hunt_number": "1"} response = self.client.post(reverse('control'), post_context) self.assertEqual(response.status_code, 302) post_context = {'action': "foobar"} response = self.client.post(reverse('control'), post_context) self.assertEqual(response.status_code, 404)
def test_make_fetcher(): symmetric362 = SPHERE_FILES['symmetric362'] with TemporaryDirectory() as tmpdir: stored_md5 = fetcher._get_file_md5(symmetric362) # create local HTTP Server testfile_url = op.split(symmetric362)[0] + os.sep test_server_url = "http://127.0.0.1:8000/" print(testfile_url) print(symmetric362) current_dir = os.getcwd() # change pwd to directory containing testfile. os.chdir(testfile_url) server = HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler) server_thread = Thread(target=server.serve_forever) server_thread.deamon = True server_thread.start() # test make_fetcher sphere_fetcher = fetcher._make_fetcher("sphere_fetcher", tmpdir, test_server_url, [op.split(symmetric362)[-1]], ["sphere_name"], md5_list=[stored_md5]) sphere_fetcher() assert op.isfile(op.join(tmpdir, "sphere_name")) npt.assert_equal(fetcher._get_file_md5(op.join(tmpdir, "sphere_name")), stored_md5) # stop local HTTP Server server.shutdown() # change to original working directory os.chdir(current_dir)
def startHTTPServer(kwargs): try: server = HTTPServer(('', PORT_NUMBER), pybusServer) logging.info('Started pybus server on port {}'.format(PORT_NUMBER)) server.serve_forever() except Exception, e: print "Error in server: {}".format(e)
def __init__(self, runner, port=None): threading.Thread.__init__(self) self._port = port if port else self.DEFAULT_PORT address = ('localhost', self._port) logger.info("Starting Tune Server...") self._server = HTTPServer(address, RunnerHandler(runner)) self.start()
def run_server(port): try: httpd = HTTPServer(("", port), http_server) httpd.serve_forever() except Exception as e: click.echo("") Log("Error Starting Beam: %s" % (e), fg="red", bold=True) interrupt_main()
def __init__(self, runner, port=None): """Initialize HTTPServer and serve forever by invoking self.run()""" threading.Thread.__init__(self) self._port = port if port else self.DEFAULT_PORT address = ('localhost', self._port) logger.info("Starting Tune Server...") self._server = HTTPServer(address, RunnerHandler(runner)) self.daemon = True self.start()
def __init__(self, config): WebChallengeHandler.__init__(self, config) self.current_directory = os.getcwd() if "port" in config: port = int(config["port"]) else: port = 80 self.server_thread = None self.server = HTTPServer(("", port), ACMERequestHandler)
def server(): """ Runs a http server that reloads when content is updated. """ Popen(['blerg.py', 'watch']) cwd = getcwd() chdir(cwd + '/build/') handler = SimpleHTTPRequestHandler httpd = HTTPServer(('127.0.0.1', conf['server_port']), handler) print('Serving on http://127.0.0.1:' + str(conf['server_port'])) httpd.serve_forever()
def start_thread(self, port): old_path = os.getcwd() if not os.path.exists(utils.CACHE_PATH): os.mkdir(utils.CACHE_PATH) web_dir = utils.CACHE_PATH os.chdir(web_dir) self.httpd = HTTPServer(("", port), SimpleHTTPRequestHandler) utils.add_log(self.logger, 'info', "serving at port {0}".format(port)) self.httpd.serve_forever() os.chdir(old_path)
def run(self): httpd = None HTTPServer.allow_reuse_address = False try: # We "partially apply" our first argument to get the viewer object into LVRequestHandler handler = partial(LVRequestHandler, self.viewer) if self.ipv6: import socket HTTPServer.address_family = socket.AF_INET6 httpd = HTTPServer(('::', self.port), handler) #httpd = ThreadingHTTPServer(('::', self.port), handler) else: httpd = HTTPServer(('0.0.0.0', self.port), handler) #httpd = ThreadingHTTPServer(('0.0.0.0', self.port), handler) #Sync with starting thread here to ensure server thread has initialised before it continues with self._cv: self._cv.notifyAll() # Handle requests #print("Using port: ", self.port) # A timeout is needed for server to check periodically if closing httpd.timeout = 0.05 #50 millisecond timeout while self.viewer() is not None and not self._closing: httpd.handle_request() except (Exception) as e: #Try another port if e.errno == errno.EADDRINUSE: self.port += 1 self.retries -= 1 #print("Port already in use - retry ", (self.maxretries - self.retries), "Port: ", self.port) if self.retries < 1: print("Failed to start server, max retries reached") return #Try again self.run() else: print("Server start failed: ", e, e.errno, self.port)
def main(): """ Builds an http page to see images in a stream as they are created in the IMAGE_PATH specified above. """ try: # Build a server that will allow us to access it/send requests through a browser server = HTTPServer(('', PORT_NUMBER), CamHandler) print("Server started at \"http://%s:%d\"" % (HOST_NAME, PORT_NUMBER)) # Keep the server up until we close it below through a Keyboad Interruption server.serve_forever() # Command+c/Command+z will stop the server once the webpage above is also stopped. except KeyboardInterrupt: server.socket.close() print("Terminated Vision program successfully")
def main(): parser = argparse.ArgumentParser() parser.add_argument('--port', '-p', default=8000, type=int) parser.add_argument('--dir', '-d', default=os.path.dirname(os.path.realpath(__file__)), type=str) args = parser.parse_args() os.chdir(args.dir) server_address = ('', args.port) httpd = HTTPServer(server_address, SimpleHTTPRequestHandler) sa = httpd.socket.getsockname() print("Serving HTTP on %s port %s ..." % (sa[0], sa[1])) httpd.serve_forever()
def test_fetch_data(): symmetric362 = SPHERE_FILES['symmetric362'] with TemporaryDirectory() as tmpdir: md5 = fetcher._get_file_md5(symmetric362) bad_md5 = '8' * len(md5) newfile = op.join(tmpdir, "testfile.txt") # Test that the fetcher can get a file testfile_url = symmetric362 print(testfile_url) testfile_dir, testfile_name = op.split(testfile_url) # create local HTTP Server test_server_url = "http://127.0.0.1:8001/" + testfile_name current_dir = os.getcwd() # change pwd to directory containing testfile. os.chdir(testfile_dir + os.sep) # use different port as shutdown() takes time to release socket. server = HTTPServer(('localhost', 8001), SimpleHTTPRequestHandler) server_thread = Thread(target=server.serve_forever) server_thread.deamon = True server_thread.start() files = {"testfile.txt": (test_server_url, md5)} fetcher.fetch_data(files, tmpdir) npt.assert_(op.exists(newfile)) # Test that the file is replaced when the md5 doesn't match with open(newfile, 'a') as f: f.write("some junk") fetcher.fetch_data(files, tmpdir) npt.assert_(op.exists(newfile)) npt.assert_equal(fetcher._get_file_md5(newfile), md5) # Test that an error is raised when the md5 checksum of the download # file does not match the expected value files = {"testfile.txt": (test_server_url, bad_md5)} npt.assert_raises(fetcher.FetcherError, fetcher.fetch_data, files, tmpdir) # stop local HTTP Server server.shutdown() # change to original working directory os.chdir(current_dir)
def create_dv_server(challenges_dir): # We need a simple HTTP server to respond to # Boulder's domain validation requests. import os.path root_path = "/.well-known/acme-challenge/" def translate_path(path): if path.startswith(root_path): # Strip the well-known prefix so we serve only # that directory. path = path[len(root_path):] fn = os.path.join(challenges_dir, path) return fn if sys.version_info < (3, ): from BaseHTTPServer import BaseHTTPRequestHandler from SocketServer import TCPServer as HTTPServer class Handler(BaseHTTPRequestHandler): def do_GET(self): fn = translate_path(self.path) if os.path.exists(fn): self.send_response(200) self.end_headers() with open(fn) as f: self.wfile.write(f.read()) else: self.send_error(404) else: from http.server import SimpleHTTPRequestHandler from http.server import HTTPServer class Handler(SimpleHTTPRequestHandler): def translate_path(self, path): return translate_path(path) return HTTPServer(('', 5002), Handler)
def run(self): if self.root_dir: os.chdir(self.root_dir) wrap = RebuildHandlerWrapper(self.change_handler, self.watch_dirs, self.work_dir) req_handler = wrap.request_handler HTTPServer.allow_reuse_address = True server = HTTPServer((self.host, self.port), req_handler) socket_info = server.socket.getsockname() print("Starting dev server on http://%s:%s... (Ctrl-C to stop)" % (socket_info[0], socket_info[1])) print("Serving files from", self.root_dir) try: server.serve_forever() except KeyboardInterrupt: print("\nStopping development server...") finally: server.shutdown()
if __name__ == "__main__": logging.basicConfig(format='%(asctime)s %(levelname)-8s: %(message)s', level=logging.DEBUG) logging.info(platform.python_version()) logging.debug(sys.argv) port = int(sys.argv[1]) app_id = sys.argv[2] version = sys.argv[3] base_url = sys.argv[4] task_id = os.getenv("MESOS_TASK_ID", "<UNKNOWN>") # Defer binding and activating the server to a later point, allowing to set # allow_reuse_address=True option. httpd = HTTPServer(("", port), make_handler(app_id, version, task_id, base_url), bind_and_activate=False) httpd.allow_reuse_address = True msg = "AppMock[%s %s]: %s has taken the stage at port %d. "\ "Will query %s for health and readiness status." logging.info(msg, app_id, version, task_id, port, base_url) # Trigger proper shutdown on SIGTERM. def handle_sigterm(signum, frame): logging.warning( "Received {} signal. Closing the server...".format(signum)) httpd.server_close() signal.signal(signal.SIGTERM, handle_sigterm)
def test_fetch_data(): symmetric362 = SPHERE_FILES['symmetric362'] with TemporaryDirectory() as tmpdir: md5 = fetcher._get_file_md5(symmetric362) bad_md5 = '8' * len(md5) newfile = op.join(tmpdir, "testfile.txt") # Test that the fetcher can get a file testfile_url = symmetric362 print(testfile_url) testfile_dir, testfile_name = op.split(testfile_url) # create local HTTP Server test_server_url = "http://127.0.0.1:8001/" + testfile_name current_dir = os.getcwd() # change pwd to directory containing testfile. os.chdir(testfile_dir + os.sep) # use different port as shutdown() takes time to release socket. server = HTTPServer(('localhost', 8001), SimpleHTTPRequestHandler) server_thread = Thread(target=server.serve_forever) server_thread.deamon = True server_thread.start() files = {"testfile.txt": (test_server_url, md5)} try: fetcher.fetch_data(files, tmpdir) except Exception as e: print(e) # stop local HTTP Server server.shutdown() npt.assert_(op.exists(newfile)) # Test that the file is replaced when the md5 doesn't match with open(newfile, 'a') as f: f.write("some junk") try: fetcher.fetch_data(files, tmpdir) except Exception as e: print(e) # stop local HTTP Server server.shutdown() npt.assert_(op.exists(newfile)) npt.assert_equal(fetcher._get_file_md5(newfile), md5) # Test that an error is raised when the md5 checksum of the download # file does not match the expected value files = {"testfile.txt": (test_server_url, bad_md5)} npt.assert_raises(fetcher.FetcherError, fetcher.fetch_data, files, tmpdir) # stop local HTTP Server server.shutdown() # change to original working directory os.chdir(current_dir) def test_dipy_home(): test_path = 'TEST_PATH' if 'DIPY_HOME' in os.environ: old_home = os.environ['DIPY_HOME'] del os.environ['DIPY_HOME'] else: old_home = None reload(fetcher) npt.assert_string_equal(fetcher.dipy_home, op.join(os.path.expanduser('~'), '.dipy')) os.environ['DIPY_HOME'] = test_path reload(fetcher) npt.assert_string_equal(fetcher.dipy_home, test_path) # return to previous state if old_home: os.environ['DIPY_HOME'] = old_home
return self.handle_ping() except: logging.exception('Could not handle POST request') raise return Handler if __name__ == "__main__": logging.basicConfig(format='%(asctime)s %(levelname)-8s: %(message)s', level=logging.DEBUG) logging.info(platform.python_version()) logging.debug(sys.argv) port = int(sys.argv[1]) taskId = os.getenv("MESOS_TASK_ID", "<UNKNOWN>") HTTPServer.allow_reuse_address = True httpd = HTTPServer(("", port), make_handler()) msg = "AppMock[%s]: has taken the stage at port %d. " logging.info(msg, taskId, port) try: httpd.serve_forever() except KeyboardInterrupt: pass logging.info("Shutting down.") httpd.shutdown() httpd.socket.close()
return Handler if __name__ == "__main__": logging.basicConfig( format='%(asctime)s %(levelname)-8s: %(message)s', level=logging.DEBUG) logging.info(platform.python_version()) logging.debug(sys.argv) port = int(sys.argv[1]) app_id = sys.argv[2] version = sys.argv[3] base_url = sys.argv[4] task_id = os.getenv("MESOS_TASK_ID", "<UNKNOWN>") HTTPServer.allow_reuse_address = True httpd = HTTPServer(("", port), make_handler(app_id, version, task_id, base_url)) msg = "AppMock[%s %s]: %s has taken the stage at port %d. "\ "Will query %s for health and readiness status." logging.info(msg, app_id, version, task_id, port, base_url) try: httpd.serve_forever() except KeyboardInterrupt: pass logging.info("Shutting down.") httpd.shutdown() httpd.socket.close()
def __init__(self, request_handler_cls): self.server = HTTPServer(('localhost', 0), request_handler_cls) self.thread = Thread(target=self.server.serve_forever) self.thread.daemon = True
#!/usr/bin/env python # -*- coding: utf-8 -*- """launch small http server """ import sys try: from SimpleHTTPServer import SimpleHTTPRequestHandler except ImportError: from http.server import SimpleHTTPRequestHandler try: from SocketServer import TCPServer as HTTPServer except ImportError: from http.server import HTTPServer # simple web server # serves files relative to the current directory. server_port = 8080 try: server_port = int(sys.argv[1]) except: pass httpd = HTTPServer(("", server_port), SimpleHTTPRequestHandler) print("serving at port {0}".format(server_port)) httpd.serve_forever()
def __init__(self, directory, port=8080): super(Server, self).__init__() HTTPServer.allow_reuse_address = True server_address = ('127.0.0.1', port) self.httpd = HTTPServer(server_address, HTTPRequestHandlerGenerator(directory))
def serve_snap(port): os.chdir( os.path.join(DOWNLOAD_FOLDER, FOLDER_PATT % load_meta()["version"])) server_address = ('', port) httpd = HTTPServer(server_address, SimpleHTTPRequestHandler) httpd.serve_forever()
xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types" /> </soap:Header> <soap:Body> <BogusResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types" xmlns="http://schemas.microsoft.com/exchange/services/2006/messages"> <m:ResponseMessages> <m:BogusResponseMessage ResponseClass="Success"> <m:ResponseCode>NoError</m:ResponseCode> </m:BogusResponseMessage> </m:ResponseMessages> </BogusResponse> </soap:Body> </soap:Envelope> """ if PYTHON_VERSION is 3: response = bytes(response_string, "utf-8") else: response = response_string self.wfile.write(response) def do_POST(self): self.do_GET() def log_message(self, format, *args): return server = HTTPServer(("localhost", 8080), Handler) server.serve_forever()
return Handler if __name__ == "__main__": logging.basicConfig(format='%(asctime)s %(levelname)-8s: %(message)s', level=logging.DEBUG) logging.info(platform.python_version()) logging.debug(sys.argv) port = int(sys.argv[1]) appId = sys.argv[2] version = sys.argv[3] url = "{}/{}".format(sys.argv[4], port) taskId = os.getenv("MESOS_TASK_ID", "<UNKNOWN>") HTTPServer.allow_reuse_address = True httpd = HTTPServer(("", port), make_handler(appId, version, url)) msg = "AppMock[%s %s]: %s has taken the stage at port %d. "\ "Will query %s for health status." logging.info(msg, appId, version, taskId, port, url) try: httpd.serve_forever() except KeyboardInterrupt: pass logging.info("Shutting down.") httpd.shutdown() httpd.socket.close()
def __init__(self, port=80): HTTPServer.allow_reuse_address = True self.server = HTTPServer(("", port), ACMERequestHandler)
except: logging.exception('Could not handle POST request') raise return Handler if __name__ == "__main__": logging.basicConfig( format='%(asctime)s %(levelname)-8s: %(message)s', level=logging.DEBUG) logging.info(platform.python_version()) logging.debug(sys.argv) port = int(sys.argv[1]) taskId = os.getenv("MESOS_TASK_ID", "<UNKNOWN>") HTTPServer.allow_reuse_address = True httpd = HTTPServer(("", port), make_handler(datetime.datetime.now())) msg = "AppMock[%s]: has taken the stage at port %d. " logging.info(msg, taskId, port) try: httpd.serve_forever() except KeyboardInterrupt: pass logging.info("Shutting down.") httpd.shutdown() httpd.socket.close()