def __init__(self, server_address, RequestHandlerClass, ssl_context=None, request_queue_size=None): # This overrides the implementation of __init__ in python's # SocketServer.TCPServer (which BaseHTTPServer.HTTPServer # does not override, thankfully). HTTPServer.__init__(self, server_address, RequestHandlerClass) self.socket = socket.socket(self.address_family, self.socket_type) self.ssl_context = ssl_context if ssl_context: class TSafeConnection(tsafe.Connection): def settimeout(self, *args): self._lock.acquire() try: return self._ssl_conn.settimeout(*args) finally: self._lock.release() def gettimeout(self): self._lock.acquire() try: return self._ssl_conn.gettimeout() finally: self._lock.release() self.socket = TSafeConnection(ssl_context, self.socket) self.server_bind() if request_queue_size: self.socket.listen(request_queue_size) self.server_activate()
def __init__(self, boat, behaviour_manager, server_address, RequestHandlerClass, bind_and_activate=True): HTTPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate) log.info('boatd api listening on %s:%s', *server_address) self.boat = boat self.behaviour_manager = behaviour_manager self.running = True # set API endpoints for GETs self.handles = { '/': self.boatd_info, '/boat': self.boat_attr, '/wind': self.wind, '/active': self.boat_active, '/behaviours': self.behaviours, } # set API endpoints for POSTs self.post_handles = { '/': self.boatd_post, '/behaviours': self.behaviours_post, }
class HTTPLogServer(threading.Thread): class RequestHandler(BaseHTTPRequestHandler): INDENT = 4 def do_GET(self): if self.path == "/summary": self.send_response(200) self.end_headers() with self.server.state_lock: status = { "complete": self.server.state["complete"], "running" : self.server.state["running"], "total" : self.server.state["total"], "results" : self.server.state["summary"], } self.wfile.write(json.dumps(status, indent=self.INDENT)) else: self.send_response(404) self.end_headers() def __init__(self, state, state_lock): super(HTTPLogServer, self).__init__() port = int(PIGLIT_CONFIG.safe_get("http", "port", fallback=8080)) self._httpd = HTTPServer(("", port), HTTPLogServer.RequestHandler) self._httpd.state = state self._httpd.state_lock = state_lock def run(self): while True: with self._httpd.state_lock: # stop handling requests after the request for the final results if self._httpd.state["complete"] == self._httpd.state["total"]: break; self._httpd.handle_request()
def __init__(self, patroni, config): self.connection_string = 'http://{}/patroni'.format(config.get('connect_address', None) or config['listen']) host, port = config['listen'].split(':') HTTPServer.__init__(self, (host, int(port)), RestApiHandler) Thread.__init__(self, target=self.serve_forever) self._set_fd_cloexec(self.socket) self.patroni = patroni self.daemon = True
def __init__(self, addr, handler, root, userpwd): HTTPServer.__init__(self, addr, handler) self.root = root self.userpwd = userpwd # WebDAV Auth user:passwd if len(userpwd)>0: self.auth_enable = True else: self.auth_enable = False
def __init__(self, server_address, handler, impl, meta): ''' :param server_address: address of the server :param handler: handler for requests :param impl: reference to the implementation object ''' HTTPServer.__init__(self, server_address, handler) self.impl = impl self.meta = meta
def start_webserver(): """Start the webserver. """ path = os.path.dirname(__file__) os.chdir(path) server_address = ("127.0.0.1", 0) httpd = HTTPServer(server_address, CGIHTTPRequestHandler) print("http://127.0.0.1:%d" % httpd.server_port) httpd.serve_forever()
def HelpServer(): global server while 1: try: server = HTTPServer(('localhost', PORT_NUMBER), HelpHandler) server.serve_forever( poll_interval = 2 ) except Exception as e: server = None time.sleep( 5 )
def __init__(self, store, *args, **kwargs): HTTPServer.__init__(self, *args, **kwargs) self.sessions = {} self.store = store if self.server_port != 80: self.base_url = ('http://%s:%s/' % (self.server_name, self.server_port)) else: self.base_url = 'http://%s/' % (self.server_name,)
class ProxyThread(threading.Thread): def __init__(self, token): self.proxy = HTTPServer(('localhost', 0), ProxyHandler) self.proxy._dcos_auth_token = token super(ProxyThread, self).__init__() def run(self): self.proxy.serve_forever() def port(self): return self.proxy.socket.getsockname()[1]
def __init__(self, *args, **kwargs): HTTPServer.__init__(self, *args, **kwargs) if self.server_port != 80: self.base_url = ('http://%s:%s/' % (self.server_name, self.server_port)) else: self.base_url = 'http://%s/' % (self.server_name,) self.openid = None self.approved = {} self.lastCheckIDRequest = {}
def run(self): """ Runs the server using Python's simple HTTPServer. TODO: make this multithreaded. """ httpd = HTTPServer((self.host, self.port), self._Handler) sa = httpd.socket.getsockname() serve_message = "Serving HTTP on {host} port {port} (http://{host}:{port}/) ..." print(serve_message.format(host=sa[0], port=sa[1])) try: httpd.serve_forever() except KeyboardInterrupt: print("\nKeyboard interrupt received, exiting.") httpd.shutdown()
def run_echo_server(): class Handler(BaseHTTPRequestHandler): def _do(self): self.send_response(200) self.send_header('Content-type', 'application/json') self.end_headers() parsed = urlparse(self.path) query_parameters = parse_qs(parsed.query) response = { 'path': parsed.path, 'headers': dict(self.headers) } if query_parameters: response['query_params'] = query_parameters try: try: # py2 raw_content_len = self.headers.getheader('content-length') except AttributeError: # py3 raw_content_len = self.headers.get('content-length') content_len = int(raw_content_len) except TypeError: content_len = 0 if content_len: body = self.rfile.read(content_len) try: # py3 body = body.decode('UTF-8') except AttributeError: # py2 pass if body: response['body'] = body print(response) encoded_json = json.dumps(response) self.wfile.write(b(encoded_json)) return do_GET = _do do_POST = _do do_PUT = _do do_HEAD = _do do_PATCH = _do do_OPTIONS = _do do_DELETE = _do do_TRACE = _do do_CONNECT = _do server_address = ('', PORT) httpd = HTTPServer(server_address, Handler) httpd.serve_forever()
def get_request(self): socket, client_address = HTTPServer.get_request(self) socket = ssl.wrap_socket(socket, keyfile=HttpsTestServerLayer.CERT_FILE, certfile=HttpsTestServerLayer.CERT_FILE, server_side=True) return socket, client_address
def __initialize(self, config): self.__ssl_options = self.__get_ssl_options(config) self.__listen = config['listen'] host, port = config['listen'].rsplit(':', 1) HTTPServer.__init__(self, (host, int(port)), RestApiHandler) Thread.__init__(self, target=self.serve_forever) self._set_fd_cloexec(self.socket) self.__protocol = 'http' # wrap socket with ssl if 'certfile' is defined in a config.yaml # Sometime it's also needed to pass reference to a 'keyfile'. if self.__ssl_options.get('certfile'): import ssl self.socket = ssl.wrap_socket(self.socket, server_side=True, **self.__ssl_options) self.__protocol = 'https' self.__set_connection_string(config.get('connect_address'))
def test(): host = 'localhost' # When I use port 0 here, it works for the first fetch and the # next one gets connection refused. Bummer. So instead, pick a # port that's *probably* not in use. import os port = (os.getpid() % 31000) + 1024 server = HTTPServer((host, port), FetcherTestHandler) import threading server_thread = threading.Thread(target=server.serve_forever) server_thread.setDaemon(True) server_thread.start() run_fetcher_tests(server) server.shutdown()
class SimpleWebServer(object): """A very basic web server.""" def __init__(self, host=DEFAULT_HOST, port=DEFAULT_PORT): self.stop_serving = False host = host port = port while True: try: self.server = HTTPServer( (host, port), HtmlOnlyHandler) self.host = host self.port = port break except socket.error: log.debug("port %d is in use, trying to next one" % port) port += 1 self.thread = threading.Thread(target=self._run_web_server) def _run_web_server(self): """Runs the server loop.""" log.debug("web server started") while not self.stop_serving: self.server.handle_request() self.server.server_close() def start(self): """Starts the server.""" self.thread.start() def stop(self): """Stops the server.""" self.stop_serving = True try: # This is to force stop the server loop URLopener().open("http://%s:%d" % (self.host, self.port)) except IOError: pass log.info("Shutting down the webserver") self.thread.join() def where_is(self, path): return "http://%s:%d/%s" % (self.host, self.port, path)
def main(ikey, skey, akey, host, port=8080): server = HTTPServer(('', port), RequestHandler) server.ikey = ikey server.skey = skey server.akey = akey server.host = host print("Visit the root URL with a 'user' argument, e.g.") print("'http://localhost:%d/?user=myname'." % port) server.serve_forever()
def __init__(self, patroni, config): self._auth_key = base64.b64encode(config['auth'].encode('utf-8')).decode('utf-8') if 'auth' in config else None host, port = config['listen'].split(':') HTTPServer.__init__(self, (host, int(port)), RestApiHandler) Thread.__init__(self, target=self.serve_forever) self._set_fd_cloexec(self.socket) protocol = 'http' # wrap socket with ssl if 'certfile' is defined in a config.yaml # Sometime it's also needed to pass reference to a 'keyfile'. options = {option: config[option] for option in ['certfile', 'keyfile'] if option in config} if options.get('certfile'): import ssl self.socket = ssl.wrap_socket(self.socket, server_side=True, **options) protocol = 'https' self.connection_string = '{0}://{1}/patroni'.format(protocol, config.get('connect_address', config['listen'])) self.patroni = patroni self.daemon = True
def __init__(self, patroni, config): self._auth_key = base64.b64encode(config["auth"].encode("utf-8")).decode("utf-8") if "auth" in config else None host, port = config["listen"].split(":") HTTPServer.__init__(self, (host, int(port)), RestApiHandler) Thread.__init__(self, target=self.serve_forever) self._set_fd_cloexec(self.socket) protocol = "http" # wrap socket with ssl if 'certfile' is defined in a config.yaml # Sometime it's also needed to pass reference to a 'keyfile'. options = {option: config[option] for option in ["certfile", "keyfile"] if option in config} if options.get("certfile", None): import ssl self.socket = ssl.wrap_socket(self.socket, server_side=True, **options) protocol = "https" self.connection_string = "{}://{}/patroni".format(protocol, config.get("connect_address", config["listen"])) self.patroni = patroni self.daemon = True
def __init__(self, port, session): self._logger = logging.getLogger(self.__class__.__name__) self.port = port self.session = session self.vod_fileindex = None self.vod_download = None self.vod_info = defaultdict(dict) # A dictionary containing info about the requested VOD streams. for _ in xrange(10000): try: HTTPServer.__init__(self, ("127.0.0.1", self.port), VideoRequestHandler) self._logger.debug("Listening at %d", self.port) break except socket.error: self._logger.debug("Listening failed at %d", self.port) self.port += 1 continue self.server_thread = None self.daemon_threads = True self.allow_reuse_address = True
def _zero_instance_app_through_http(): class JSONRequestHandler (BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header("Content-type", "application/json") self.end_headers() self.wfile.write(open( 'tests/data/marathon/apps/zero_instance_sleep.json', 'rb').read()) host = 'localhost' port = 12345 server = HTTPServer((host, port), JSONRequestHandler) thread = threading.Thread(target=server.serve_forever) thread.setDaemon(True) thread.start() with app('http://{}:{}'.format(host, port), 'zero-instance-app'): try: yield finally: server.shutdown()
def main(argv): import getopt, imp def usage(): print ('usage: %s [-h host] [-p port] [-n name] module.class' % argv[0]) return 100 try: (opts, args) = getopt.getopt(argv[1:], 'h:p:n:') except getopt.GetoptError: return usage() host = '' port = 8080 name = 'WebApp' for (k, v) in opts: if k == '-h': host = v elif k == '-p': port = int(v) elif k == '-n': name = v if not args: return usage() path = args.pop(0) module = imp.load_source('app', path) WebAppHandler.APP_CLASS = getattr(module, name) print ('Listening %s:%d...' % (host,port)) httpd = HTTPServer((host,port), WebAppHandler) httpd.serve_forever() return
def __init__(self, host=DEFAULT_HOST, port=DEFAULT_PORT): self.stop_serving = False host = host port = port while True: try: self.server = HTTPServer( (host, port), HtmlOnlyHandler) self.host = host self.port = port break except socket.error: log.debug("port %d is in use, trying to next one" % port) port += 1 self.thread = threading.Thread(target=self._run_web_server)
def oauth_server(): # Start the OAuth server on a random port in the background server = HTTPServer(('', 0), OAuthHandler) server.url = 'http://{0}:{1}/'.format(*server.server_address) thread = threading.Thread(target=server.serve_forever) thread.start() try: yield server finally: server.shutdown() thread.join() server.server_close()
def __init__(self, client, subscription_manager, *args, **kwargs): self.client = client self.subscription_manager = subscription_manager HTTPServer.__init__(self, *args, **kwargs)
resp_data['primary_calendar_events'] = ( primary_calendar_events.data) self.send_response(200) self.send_header("Content-type", "application/json") self.end_headers() self.wfile.write(json.dumps(resp_data).encode('utf8')) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('app_id', type=str, help='You can access app_id via https://developers.klo' 'udless.com/applications/*/details') parser.add_argument('api_key', type=str, help='You can access api_key via https://developers.klo' 'udless.com/applications/*/details') parser.add_argument('--port', type=int, default=8020, help='Port number to run the server, default to 8020') args = parser.parse_args() app_id = args.app_id api_key = args.api_key port = args.port print('Listening on localhost:%s' % port) httpd = HTTPServer(('', port), RequestHandler) httpd.serve_forever()
def __init__(self, server_address, request_handler, path): self.path = path HTTPServer.__init__(self, server_address, request_handler)
def server_bind(self): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) HTTPServer.server_bind(self)
def __init__(self, server, routes=(), static_dirs=(), *args, **kwargs): self._server = server self._routes.extend(routes) self._static_dirs.extend(static_dirs) HTTPServer.__init__(self, *args, **kwargs)
def __init__(self, token, dispatcher): self.proxy = HTTPServer(('localhost', 0), ProxyHandler) self.proxy.dispatcher = dispatcher self.proxy._dcos_auth_token = token super(ProxyThread, self).__init__()
def __init__(self, server_address, RequestHandlerClass, client_id, client_secret, bind_and_activate=True): HTTPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate=bind_and_activate) self.logger = logging.getLogger('auth_server.http') self.client_id = client_id self.client_secret = client_secret self.listening_event = threading.Event()
__test__ = False if __name__ == '__main__': import eventlet eventlet.monkey_patch() from six.moves.BaseHTTPServer import ( HTTPServer, BaseHTTPRequestHandler, ) import threading server = HTTPServer(('localhost', 0), BaseHTTPRequestHandler) thread = threading.Thread(target=server.serve_forever) # Before fixing it the code would never go pass this line because: # * socketserver.BaseServer that's used behind the scenes here uses # selectors.PollSelector if it's available and we don't have green poll # implementation so this just couldn't work # * making socketserver use selectors.SelectSelector wasn't enough as # until now we just failed to monkey patch selectors module # # Due to the issues above this thread.start() call effectively behaved # like calling server.serve_forever() directly in the current thread # # Original report: https://github.com/eventlet/eventlet/issues/249 thread.start() server.shutdown() print('pass')
def authorize(self): self.params.update(state=None, code=None, error=None) # If we already have a token, request new access credentials if self.config.refresh_token: with self.term.loader('Logging in'): self.reddit.refresh_access_information( self.config.refresh_token) return state = uuid.uuid4().hex authorize_url = self.reddit.get_authorize_url( state, scope=self.config['oauth_scope'], refreshable=True) if self.server is None: address = ('', self.config['oauth_redirect_port']) self.server = HTTPServer(address, OAuthHandler) if self.term.display: # Open a background browser (e.g. firefox) which is non-blocking. # The server will block until it responds to its first request, # at which point we can check the callback params. OAuthHandler.shutdown_on_request = True with self.term.loader('Opening browser for authorization'): self.term.open_browser(authorize_url) self.server.serve_forever() if self.term.loader.exception: # Don't need to call server.shutdown() because serve_forever() # is wrapped in a try-finally that doees it for us. return else: # Open the terminal webbrowser in a background thread and wait # while for the user to close the process. Once the process is # closed, the iloop is stopped and we can check if the user has # hit the callback URL. OAuthHandler.shutdown_on_request = False with self.term.loader('Redirecting to reddit', delay=0): # This load message exists to provide user feedback time.sleep(1) thread = threading.Thread(target=self.server.serve_forever) thread.daemon = True thread.start() try: self.term.open_browser(authorize_url) except Exception as e: # If an exception is raised it will be seen by the thread # so we don't need to explicitly shutdown() the server _logger.exception(e) self.term.show_notification('Browser Error') else: self.server.shutdown() finally: thread.join() if self.params['error'] == 'access_denied': self.term.show_notification('Denied access') return elif self.params['error']: self.term.show_notification('Authentication error') return elif self.params['state'] is None: # Something went wrong but it's not clear what happened return elif self.params['state'] != state: self.term.show_notification('UUID mismatch') return with self.term.loader('Logging in'): info = self.reddit.get_access_information(self.params['code']) if self.term.loader.exception: return message = 'Welcome {}!'.format(self.reddit.user.name) self.term.show_notification(message) self.config.refresh_token = info['refresh_token'] if self.config['persistent']: self.config.save_refresh_token()
def http_serv_obj(): """ Return an HTTP object listening on localhost port 80 for testing """ return HTTPServer(('localhost', 80), SimpleHTTPRequestHandler)
self.wfile.write(f.read()) except IOError: self.send_response(404) self.end_headers() def do_auth(self, src): # Combine 'src' from query with demo user configuration, host and secret to create signed url # Any session validation should happen here. url = create_signed_url(src, user, HOST, SECRET) # Return signed url as json blob {"url":"<signed_url>"} self.send_response(200) self.end_headers() self.wfile.write(json.dumps({'url': url}).encode()) # Override simple GET callback def do_GET(self): parts = urlparse(self.path) query = parse_qs(parts.query) if parts.path == '/auth': self.do_auth(query['src'][0]) else: self.do_file(parts.path) httpd = HTTPServer((DEMO_HOST, DEMO_PORT), SimpleHTTPRequestHandler) print('Server listening on %s:%s' % (DEMO_HOST, DEMO_PORT)) httpd.serve_forever()
def __init__(self, address, handler): HTTPServer.__init__(self, address, handler) self.response_queue = queue.Queue()
def serve_forever(self, *args, **kwargs): self.listening_event.set() return HTTPServer.serve_forever(self, *args, **kwargs)
def thread_run(task_runner=None): task_runner.server = HTTPServer(address, HTTPHandlerGen(task_runner)) task_runner.server.allow_reuse_address = True task_runner.server.serve_forever()
if process.returncode: raise Exception("%s failed to start" % (appname, )) # Nothing failed, let's say we've started and then signal we're up by # serving the webserver. _print("Synapse started!") class WebHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.end_headers() self.wfile.write("OK") return PORT_NUMBER = int(args["--addr"].split(":")[1]) server = HTTPServer(('', PORT_NUMBER), WebHandler) server.serve_forever() except KeyboardInterrupt: pass except BaseException as e: # Log a traceback for debug import traceback traceback.print_exc() # If we get told to shut down, log it _print("Told to quit because %s" % (repr(e))) # Otherwise, something bad has happened. sys.exit(1) finally:
class IPCamTrendnetTvIp100Service(ServerCustomService): """IP Cam TRENDnet TV-IP100 Service.""" httpd = None def alert(self, request, event): """Raise an alert.""" params = { EVENT_TYPE_FIELD_NAME: event, ORIGINATING_IP_FIELD_NAME: request.client_address[0], ORIGINATING_PORT_FIELD_NAME: request.client_address[1], REQUEST_FIELD_NAME: " ".join([request.command, request.path]), } self.add_alert_to_queue(params) def on_server_start(self): """Initialize Service.""" os.chdir(os.path.join(os.path.dirname(__file__), "www")) requestHandler = TrendnetTVIP100CamRequestHandler requestHandler.alert = self.alert requestHandler.logger = self.logger requestHandler.server_version = self.service_args.get("version", DEFAULT_SERVER_VERSION) requestHandler.image_src_url = self.service_args.get("image_src_url", None) requestHandler.image_src_path = self.service_args.get("image_src_path", None) if requestHandler.image_src_path and requestHandler.image_src_url: raise ValueError("cannot process both image_src_path and image_src_url") if not requestHandler.image_src_path and not requestHandler.image_src_url: raise ValueError("image_src_path or image_src_url must be provided") port = self.service_args.get("port") threading = self.service_args.get("threading", False) if threading: self.httpd = ThreadingHTTPServer(("", port), requestHandler) else: self.httpd = HTTPServer(("", port), requestHandler) self.signal_ready() self.logger.info( "Starting {}IP Cam TRENDnet TV-IP100 service on port: {}".format("Threading " if threading else "", port)) self.httpd.serve_forever() def on_server_shutdown(self): """Shut down gracefully.""" if self.httpd: self.httpd.shutdown() self.logger.info("IP Cam TRENDnet TV-IP100 service stopped") self.httpd = None def test(self): """Test service alerts and return a list of triggered event types.""" event_types = list() self.logger.debug("executing service test") # basic screen requests.get("http://localhost:{}".format(self.service_args.get("port"))) # camera shot requests.get("http://localhost:{}{}".format(self.service_args.get("port"), CAMERA_IMAGE_PATH)) # Invalid url requests.get("http://localhost:{}/asdasdad.html".format(self.service_args.get("port"))) # / redirect requests.get("http://localhost:{}/".format(self.service_args.get("port"))) # One alert for authorization attempt requests.get("http://localhost:{}/content.html".format(self.service_args.get("port")), headers={"Authorization": "username=\"test\""}) event_types.append(TRENDNET_ADMIN_ACCESS_EVENT) # And for POST requests.post("http://localhost:{}/content.html".format(self.service_args.get("port")), data={}) event_types.append(TRENDNET_ADMIN_POST_ATTEMPT) return event_types def __str__(self): return "IP Cam TRENDnet TV-IP100"
def _multiproc_serve_path_via_http(hostname, path_to_serve_from, queue): # pragma: no cover chpwd(path_to_serve_from) httpd = HTTPServer((hostname, 0), SilentHTTPHandler) queue.put(httpd.server_port) httpd.serve_forever()
class OAuthHelper(object): params = OAuthHandler.params def __init__(self, reddit, term, config): self.term = term self.reddit = reddit self.config = config # Wait to initialize the server, we don't want to reserve the port # unless we know that the server needs to be used. self.server = None self.reddit.set_oauth_app_info(self.config['oauth_client_id'], self.config['oauth_client_secret'], self.config['oauth_redirect_uri']) # Reddit's mobile website works better on terminal browsers if not self.term.display: if '.compact' not in self.reddit.config.API_PATHS['authorize']: self.reddit.config.API_PATHS['authorize'] += '.compact' def authorize(self): self.params.update(state=None, code=None, error=None) # If we already have a token, request new access credentials if self.config.refresh_token: with self.term.loader('Logging in'): try: self.reddit.refresh_access_information( self.config.refresh_token) except (HTTPException, OAuthException) as e: # Reddit didn't accept the refresh-token # This appears to throw a generic 400 error instead of the # more specific invalid_token message that it used to send if isinstance(e, HTTPException): if e._raw.status_code != 400: # No special handling if the error is something # temporary like a 5XX. raise e # Otherwise we know the token is bad, so we can remove it. _logger.exception(e) self.clear_oauth_data() raise InvalidRefreshToken( ' Invalid user credentials!\n' 'The cached refresh token has been removed') return state = uuid.uuid4().hex authorize_url = self.reddit.get_authorize_url( state, scope=self.config['oauth_scope'], refreshable=True) if self.server is None: address = ('', self.config['oauth_redirect_port']) self.server = HTTPServer(address, OAuthHandler) if self.term.display: # Open a background browser (e.g. firefox) which is non-blocking. # The server will block until it responds to its first request, # at which point we can check the callback params. OAuthHandler.shutdown_on_request = True with self.term.loader('Opening browser for authorization'): self.term.open_browser(authorize_url) self.server.serve_forever() if self.term.loader.exception: # Don't need to call server.shutdown() because serve_forever() # is wrapped in a try-finally that doees it for us. return else: # Open the terminal webbrowser in a background thread and wait # while for the user to close the process. Once the process is # closed, the iloop is stopped and we can check if the user has # hit the callback URL. OAuthHandler.shutdown_on_request = False with self.term.loader('Redirecting to reddit', delay=0): # This load message exists to provide user feedback time.sleep(1) thread = threading.Thread(target=self.server.serve_forever) thread.daemon = True thread.start() try: self.term.open_browser(authorize_url) except Exception as e: # If an exception is raised it will be seen by the thread # so we don't need to explicitly shutdown() the server _logger.exception(e) self.term.show_notification('Browser Error', style='error') else: self.server.shutdown() finally: thread.join() if self.params['error'] == 'access_denied': self.term.show_notification('Denied access', style='error') return elif self.params['error']: self.term.show_notification('Authentication error', style='error') return elif self.params['state'] is None: # Something went wrong but it's not clear what happened return elif self.params['state'] != state: self.term.show_notification('UUID mismatch', style='error') return with self.term.loader('Logging in'): info = self.reddit.get_access_information(self.params['code']) if self.term.loader.exception: return message = 'Welcome {}!'.format(self.reddit.user.name) self.term.show_notification(message) self.config.refresh_token = info['refresh_token'] if self.config['persistent']: self.config.save_refresh_token() def clear_oauth_data(self): self.reddit.clear_authentication() self.config.delete_refresh_token()
def server_close(self): self.socket.shutdown(socket.SHUT_RDWR) HTTPServer.server_close(self) self.__methods__.clear() log("httpd: server stopped")
#!/usr/bin/env python import textwrap from six.moves.BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class HelloRequestHandler(BaseHTTPRequestHandler): def do_GET(self): if self.path != '/': self.send_error(404, "Object not found") return self.send_response(200) self.send_header('Content-type', 'text/html; charset=utf-8') self.end_headers() response_text = textwrap.dedent('''\ <html> <body> <p>Hello World from Pure Python example!</p> </body> </html> ''') self.wfile.write(response_text.encode('utf-8')) server_address = ('', 9000) httpd = HTTPServer(server_address, HelloRequestHandler) httpd.serve_forever()
def __init__(self, timeout=-1): self.timeout = None if timeout < 0 else timeout self.__methods__ = {} self.__methods__.update(self._setup(self)) HTTPServer.__init__(self, self._localhost(), RequestHandler) log("httpd: server started on: {}".format(self.server_address))
def __init__(self, RequestHandlerClass): HTTPServer.__init__(self, None, RequestHandlerClass, False) self.requestHandler = RequestHandlerClass self.queue = TaskQueue("http-server", _MAX_QUEUE_TASKS)
def __init__(self, state, state_lock): super(HTTPLogServer, self).__init__() port = int(PIGLIT_CONFIG.safe_get("http", "port", fallback=8080)) self._httpd = HTTPServer(("", port), HTTPLogServer.RequestHandler) self._httpd.state = state self._httpd.state_lock = state_lock
else: self.http_json_response(200, resp_data) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('app_id', type=str, help='You can access app_id via https://developers.klo' 'udless.com/applications/*/details') parser.add_argument( 'api_key', type=str, help='You can access api_key via https://developers.klo' 'udless.com/applications/*/details') parser.add_argument('--port', type=int, default=8020, help='Port number to run the server, default to 8020') args = parser.parse_args() app_id = args.app_id api_key = args.api_key port = args.port print('Listening on localhost:%s' % port) httpd = HTTPServer(('', port), RequestHandler) httpd.serve_forever()
def __init__(self, base_path, *args, **kwargs): HTTPServer.__init__(self, *args, **kwargs) self.RequestHandlerClass.base_path = base_path
def do_bind(self): """Perform HTTP server binding and activation.""" HTTPServer.__init__(self, (self.host, self.port), HTTPRequestHandler)
def finish_request(self,request,client_address): try: HTTPServer.finish_request(self, request, client_address) except socket.error as e: pass
def start_mock_server(): server_address = ('127.0.0.1', 8545) httpd = HTTPServer(server_address, MockedTestrpc) httpd.serve_forever() print('served internal')
def finish_request(self, request, client_address): try: HTTPServer.finish_request(self, request, client_address) except socket.error as e: pass
def start_local_http_server(port, handler=RequestHandler): server = HTTPServer(("127.0.0.1", port), handler) server.allow_reuse_address = True server.auth_code = None server.error = None return server