def make_simple_server(tb_app, host, port): """Create an HTTP server for TensorBoard. Args: tb_app: The TensorBoard WSGI application to create a server for. host: Indicates the interfaces to bind to ('::' or '0.0.0.0' for all interfaces, '::1' or '127.0.0.1' for localhost). A blank value ('') indicates protocol-agnostic all interfaces. port: The port to bind to (0 indicates an unused port selected by the operating system). Returns: A tuple of (server, url): server: An HTTP server object configured to host TensorBoard. url: A best guess at a URL where TensorBoard will be accessible once the server has been started. Raises: socket.error: If a server could not be constructed with the host and port specified. Also logs an error message. """ # Mute the werkzeug logging. base_logging.getLogger('werkzeug').setLevel(base_logging.WARNING) try: if host: # The user gave us an explicit host server = serving.make_server(host, port, tb_app, threaded=True) if ':' in host and not host.startswith('['): # Display IPv6 addresses as [::1]:80 rather than ::1:80 final_host = '[{}]'.format(host) else: final_host = host else: # We've promised to bind to all interfaces on this host. However, we're # not sure whether that means IPv4 or IPv6 interfaces. try: # First try passing in a blank host (meaning all interfaces). This, # unfortunately, defaults to IPv4 even if no IPv4 interface is available # (yielding a socket.error). server = serving.make_server(host, port, tb_app, threaded=True) except socket.error: # If a blank host didn't work, we explicitly request IPv6 interfaces. server = serving.make_server('::', port, tb_app, threaded=True) final_host = socket.gethostname() server.daemon_threads = True except socket.error as socket_error: if port == 0: msg = 'TensorBoard unable to find any open port' else: msg = ( 'TensorBoard attempted to bind to port %d, but it was already in use' % FLAGS.port) logging.error(msg) print(msg) raise socket_error final_port = server.socket.getsockname()[1] tensorboard_url = 'http://%s:%d' % (final_host, final_port) return server, tensorboard_url
def run(self): """Run the WSGI server in a thread.""" logging.info("Listening on port %d.", self.port) ssl_context = None if config.CONFIG["AdminUI.enable_ssl"]: cert_file = config.CONFIG["AdminUI.ssl_cert_file"] if not cert_file: raise ValueError("Need a valid cert file to enable SSL.") key_file = config.CONFIG["AdminUI.ssl_key_file"] if not key_file: raise ValueError("Need a valid key file to enable SSL.") ssl_context = (cert_file, key_file) # Werkzeug only handles IPv6 if ":" is in the host (i.e. we pass # an IPv6 ip). ip = utils.ResolveHostnameToIP("localhost", self.port) server = serving.make_server( ip, self.port, wsgiapp.AdminUIApp().WSGIHandler(), ssl_context=ssl_context) # We want to notify other threads that we are now ready to serve right # before we enter the serving loop. self.ready_to_serve.set() while self.keep_running: server.handle_request()
def _serve(self): # Load stored authentication keys self.keys = self.get_config_json("keys") or {} jsonify._instance = jsonify.GenericJSON( sort_keys=True, indent=4, separators=(',', ': '), ) cert = self.get_config_json("cert") or '/etc/ceph/ceph-mgr-restful.crt' pkey = self.get_config_json("pkey") or '/etc/ceph/ceph-mgr-restful.key' # Create the HTTPS werkzeug server serving pecan app self.server = make_server( host='0.0.0.0', port=8003, app=make_app( root='restful.api.Root', hooks = lambda: [ErrorHook()], ), ssl_context=(cert, pkey), ) self.server.serve_forever()
def inner(): # server = serving.make_server(host, app_port, self._app, # False, 1, ClientCertHTTPRequestHandler, False, # 'adhoc') server = serving.make_server( host, app_port, self._app, False, 1, ClientCertHTTPRequestHandler, False, ssl_context=context) # server = serving.make_server(host, app_port, self._app, # False, 1, ClientCertHTTPRequestHandler, # False, ssl_context=(context_crt, context_key)) # Following line is the reason why I copied all that code! if must_have_client_cert: #if must_have_client_cert or must_use_speaks_for: # FIXME: what works with webapp does not with CLI server.ssl_context.set_verify( SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT | # Ignoring certs unless SSL.VERIFY_PEER is set SSL.VERIFY_CLIENT_ONCE, lambda a, b, c, d, e: True) else: server.ssl_context.set_verify( SSL.VERIFY_NONE, lambda a, b, c, d, e: True) # Before entering loop, start supplementary services for s in services: s.start() # That's it server.serve_forever()
def inner(): server = serving.make_server(host, app_port, self._app, False, 1, ClientCertHTTPRequestHandler, False, 'adhoc') # The following line is the reason why I copied all that code! if must_have_client_cert: server.ssl_context.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, lambda a,b,c,d,e: True) # That's it server.serve_forever()
def __init__(self, credential_store, port, region, profile_name=None, kms_host=None, kms_port=None, s3_host=None, s3_port=None, s3_secure=True, kms_secure=True, aws_access_key_id=None, aws_secret_access_key=None): from werkzeug.serving import make_server super(Server, self).__init__() self.port = port if credential_store.startswith("s3://"): kms = boto.kms.connect_to_region( region, profile_name=profile_name, host=kms_host, port=kms_port, is_secure=kms_secure, aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key) kms.auth_region_name = region kms.auth_service_name = "kms" s3 = boto.s3.connect_to_region( region, profile_name=profile_name, calling_format=OrdinaryCallingFormat(), host=s3_host, port=s3_port, is_secure=s3_secure, aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key) self.read_credentials_from_s3(credential_store, kms, s3) else: self.read_credentials_from_file(credential_store) self.app = Flask("kdist.server") self.handler = Handler(self.app, region, keymap=self.credentials) self.handler.server = make_server( "", self.port, self.app, threaded=True) self.credentials = None return
def run_simple_server(tb_app): """Start serving TensorBoard, and print some messages to console.""" # Mute the werkzeug logging. base_logging.getLogger('werkzeug').setLevel(base_logging.WARNING) try: server = serving.make_server(FLAGS.host, FLAGS.port, tb_app, threaded=True) server.daemon_threads = True except socket.error: if FLAGS.port == 0: msg = 'TensorBoard unable to find any open port' else: msg = ( 'TensorBoard attempted to bind to port %d, but it was already in use' % FLAGS.port) logging.error(msg) print(msg) exit(-1) port = server.socket.getsockname()[1] msg = 'Starting TensorBoard %s at http://%s:%d' % (tb_app.tag, FLAGS.host, port) print(msg) logging.info(msg) print('(Press CTRL+C to quit)') sys.stdout.flush() server.serve_forever()
def startHelpServer(port=48626): import socket, threading from werkzeug import serving max_attempts = 20 http = None server = None server_port = port for i in range(max_attempts): try: # TODO: Use host specified by .ini configuration. server = serving.make_server("0.0.0.0", server_port, app=bookish_app) break except socket.error: server_port += 1 pass if not server: raise Exception("Could not find open port for help server.") serverthread = threading.Thread(target=server.serve_forever) serverthread.start() return server_port
def restart_with_reloader(): to_mon = [] while 1: _log('info', ' * Clastic restarting with reloader') args = [sys.executable] + sys.argv new_environ = os.environ.copy() new_environ['WERKZEUG_RUN_MAIN'] = 'true' if os.name == 'nt': for key, value in new_environ.iteritems(): if isinstance(value, unicode): new_environ[key] = value.encode('iso-8859-1') stderr_buff = [] child_proc = subprocess.Popen(args, env=new_environ, stderr=subprocess.PIPE) rf = child_proc.stderr exit_code, lines = None, [] while exit_code is None or lines: if child_proc.poll() is None: lines.append(rf.readline()) elif exit_code is None: lines.extend(rf.readlines()) exit_code = child_proc.returncode if not lines: break cur_line = lines.pop(0) if cur_line.startswith(_MON_PREFIX): to_mon = literal_eval(cur_line[len(_MON_PREFIX):]) else: sys.stderr.write(cur_line) stderr_buff.append(cur_line) if len(stderr_buff) > _STDERR_BUFF_SIZE: stderr_buff.pop(0) if exit_code == 3: continue elif exit_code == 1 and stderr_buff: enable_tty_echo() from clastic import flaw tb_str = ''.join(stderr_buff) err_app = flaw.create_app(tb_str, to_mon) # TODO: these values should be passed through err_server = make_server('localhost', 5000, err_app) thread.start_new_thread(err_server.serve_forever, ()) try: reloader_loop(to_mon, 1) except KeyboardInterrupt: return 0 except SystemExit as se: if se.code == 3: continue return se.code finally: err_server.shutdown() err_server.server_close() return 0 else: return exit_code
def __init__(self, app, host="", port=0, threaded=True, processes=1, request_handler=RequestHandler, passthrough_errors=False, ssl_context=None): """ Use ssl_context='adhoc' for an ad-hoc cert, a tuple for a (cerk, pkey) files """ threading.Thread.__init__(self) self.daemon=True self.server = make_server(host, port, app, threaded=threaded, processes=processes, request_handler=request_handler, passthrough_errors=passthrough_errors, ssl_context=ssl_context)
def _serve(self): # Load stored authentication keys self.refresh_keys() jsonify._instance = jsonify.GenericJSON( sort_keys=True, indent=4, separators=(',', ': '), ) server_addr = self.get_localized_config('server_addr', '::') if server_addr is None: raise RuntimeError('no server_addr configured; try "ceph config-key put mgr/restful/server_addr <ip>"') server_port = int(self.get_localized_config('server_port', '8003')) self.log.info('server_addr: %s server_port: %d', server_addr, server_port) cert = self.get_localized_config("crt") if cert is not None: cert_tmp = tempfile.NamedTemporaryFile() cert_tmp.write(cert) cert_tmp.flush() cert_fname = cert_tmp.name else: cert_fname = self.get_localized_config('crt_file') pkey = self.get_localized_config("key") if pkey is not None: pkey_tmp = tempfile.NamedTemporaryFile() pkey_tmp.write(pkey) pkey_tmp.flush() pkey_fname = pkey_tmp.name else: pkey_fname = self.get_localized_config('key_file') if not cert_fname or not pkey_fname: raise RuntimeError('no certificate configured') if not os.path.isfile(cert_fname): raise RuntimeError('certificate %s does not exist' % cert_fname) if not os.path.isfile(pkey_fname): raise RuntimeError('private key %s does not exist' % pkey_fname) # Create the HTTPS werkzeug server serving pecan app self.server = make_server( host=server_addr, port=server_port, app=make_app( root='restful.api.Root', hooks = [ErrorHook()], # use a callable if pecan >= 0.3.2 ), ssl_context=(cert_fname, pkey_fname), ) self.server.serve_forever()
def setUpPackage(): create_temp_database() apply_migrations() server = make_server('0.0.0.0', 65432, app) thread = threading.Thread(target=server.serve_forever) thread.daemon = True thread.start() web_actors['server'] = server web_actors['browser'] = SingleVisitFirefoxDriver()
def __init__(self, app, host=None, port=5869): super().__init__() @app.route('/ping', methods=['GET']) def ping(): return Response(status=200) self.host = host or os.environ.get('POD_IP', '127.0.0.1') self.port = port self.app = app self.server = make_server(self.host, self.port, app) self.context = app.app_context() self.context.push()
def __init__(self, app, host='127.0.0.1', port=5000): super().__init__() @app.route('/ping', methods=['GET']) def ping(): return Response(status=200) self.host = host self.port = port self.app = app self.server = make_server(self.host, self.port, app) self.context = app.app_context() self.context.push()
def before_all(context): # Use dev server and request vs test_client to allow running against other environments app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' app.config['TESTING'] = True host = 'localhost' port = '5000' context.base_url = 'http://' + host + ':' + port context.server = make_server(host, port, app, threaded=True) context.thread = threading.Thread(target=context.server.serve_forever) context.thread.start()
def inner(): #server = serving.make_server(host, app_port, self._app, False, 1, ClientCertHTTPRequestHandler, False, 'adhoc') server = serving.make_server(host, app_port, self._app, False, 1, ClientCertHTTPRequestHandler, False, ssl_context=context) #server = serving.make_server(host, app_port, self._app, False, 1, ClientCertHTTPRequestHandler, False, ssl_context=(context_crt, context_key)) # The following line is the reason why I copied all that code! if must_have_client_cert: # FIXME: what works with web app does not work with cli. Check this out server.ssl_context.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, lambda a,b,c,d,e: True) # before enter in the loop, start the supplementary services for s in services: s.start() # That's it server.serve_forever()
def __init__(self, keymap, kms_key_id): super(InMemoryAWSServer, self).__init__() self.port = find_open_port() self.app = Flask("test.s3_test") self.app.add_url_rule("/", "s3", self.handle_request, methods=["HEAD", "GET", "POST", "PUT"]) self.app.add_url_rule("/<path:uri>", "s3", self.handle_request, methods=["HEAD", "GET", "POST", "PUT"]) self.server = make_server("", self.port, self.app) self.buckets = {} self.keymap = keymap self.kms_key_id = kms_key_id return
def run(self): """Run the WSGI server in a thread.""" logging.info("Listening on port %d.", self.port) # Werkzeug only handles IPv6 if ":" is in the host (i.e. we pass # an IPv6 ip). ip = utils.ResolveHostnameToIP("localhost", self.port) server = serving.make_server(ip, self.port, wsgiapp.AdminUIApp().WSGIHandler()) # We want to notify other threads that we are now ready to serve right # before we enter the serving loop. self.ready_to_serve.set() while self.keep_running: server.handle_request()
def _serve(self): # Load stored authentication keys self.refresh_keys() jsonify._instance = jsonify.GenericJSON( sort_keys=True, indent=4, separators=(',', ': '), ) server_addr = self.get_localized_config('server_addr') or '127.0.0.1' server_port = int(self.get_localized_config('server_port') or '8003') self.log.info('server_addr: %s server_port: %d', server_addr, server_port) cert = self.get_localized_config("crt") if cert is not None: cert_tmp = tempfile.NamedTemporaryFile() cert_tmp.write(cert) cert_tmp.flush() cert_fname = cert_tmp.name else: cert_fname = self.get_localized_config('crt_file') or '/etc/ceph/ceph-mgr-restful.crt' pkey = self.get_localized_config("key") if pkey is not None: pkey_tmp = tempfile.NamedTemporaryFile() pkey_tmp.write(pkey) pkey_tmp.flush() pkey_fname = pkey_tmp.name else: pkey_fname = self.get_localized_config('key_file') or '/etc/ceph/ceph-mgr-restful.key' # Create the HTTPS werkzeug server serving pecan app self.server = make_server( host=server_addr, port=server_port, app=make_app( root='restful.api.Root', hooks = [ErrorHook()], # use a callable if pecan >= 0.3.2 ), ssl_context=(cert_fname, pkey_fname), ) self.server.serve_forever()
def run_app(app, host="dev.example.com", port=4566, run_app=True): # for convenience in setting up OAuth ids and secretes we use the example.com domain. # This should allow you to circumvent limits put on localhost/127.0.0.1 usage # Just map dev.example.com on 127.0.0.1 ip address. logging.debug("app.debug: %s" % app.debug) logging.debug("app.testing: %s" % app.testing) logging.debug("run_app: %s" % run_app) logging.debug("Don't forget to map %s on 127.0.0.1 ip address", host) if not run_app: # we want to just return a server # in order to do that we need to recreate some of werkzeug functionality from werkzeug.serving import make_server server = make_server(host, port, app) return server return app.run(host, port, app)
def start_sever(self, config): app = Flask("FlaskServer") app.json_encoder = CustomJSONEncoder for blueprint in self.blueprints: app.register_blueprint(blueprint) c = config.flask app.secret_key = c.secret_key FlaskBundle.app = app if c.cors: CORS(app) if c.debug: kernel = inject.instance(Kernel) if kernel.environment != Environments.TEST: self.srv = make_server(c.host, c.port, app) ctx = app.app_context() ctx.push() self.srv.serve_forever()
def __init__(self, app): Thread.__init__(self) self.srv = make_server('localhost', 5000, app) self.ctx = app.app_context() self.ctx.push()
def __init__(self, app): threading.Thread.__init__(self) self.srv = make_server(host="0.0.0.0", port=3000, app=app) self.ctx = app.app_context() self.ctx.push() _logger.debug("ServerThread Class Initialized")
output = get_tensor_data(prediction) prediction = trim(output[0].tolist()) return sp.DecodeIds(prediction) @Request.application def application(request): url_path = request.path if url_path == '/translate': source = request.args['source'] target = translate(source) translation_html_data = open('webservice/translate.html', 'r', encoding='utf-8').read() return Response(Template(translation_html_data).render(source=source, target=target), status='200 OK', content_type='text/html') translation_html_data = open('webservice/index.html', 'rb').read() return Response(translation_html_data, status='200 OK', content_type='text/html') if __name__ == '__main__': server = make_server('0.0.0.0', 4000, application) server.serve_forever() # from werkzeug.serving import run_simple # # run_simple('0.0.0.0', 4000, application)
def start(self): self.server = make_server('0.0.0.0', 65432, self.app) self.server.serve_forever()
def _server_entry(self): app = DomainDispatcherApplication(create_backend_app) self._server = make_server(self._ip_address, self._port, app, True) self._server_ready = True self._server.serve_forever()
def __init__(self, app, port, auth_func): threading.Thread.__init__(self) self.srv = make_server('127.0.0.1', port, app) self.auth_func = auth_func self.ctx = app.app_context() self.ctx.push()
def startServerAdminCard(exitFlag): oldAdminCard = Utils.settings["odooParameters"]["admin_id"][0].lower() app = Flask("odoo_new_admin_card") app.secret_key = os.urandom(12) Utils.getOwnIpAddress() srv = make_server(str(Utils.settings["ownIpAddress"][0]), 3000, app) ctx = app.app_context() ctx.push() server = ServerThread(srv) server.start() @app.route("/") def form(): if session.get("logged_in"): return render_template("reset_admin_form.html", IP=str(Utils.settings["ownIpAddress"][0]), port=3000) else: return render_template("loginNewAdminCard.html", IP=str(Utils.settings["ownIpAddress"][0]), port=3000) @app.route("/loginNewAdminCard", methods=["POST", "GET"]) def doLogin(): if request.method == "POST": if request.form.get("Log in") == "Log in": if (request.form["password"] == Utils.settings["flask"] ["new password"][0]): session["logged_in"] = True return form() else: #flash("wrong password!") return form() else: return form() else: return form() @app.route("/adminCardChanged", methods=["POST", "GET"]) def result(): if request.method == "POST": if request.form.get("Log in") == "Log in": return form() else: results = request.form dic = results.to_dict(flat=False) newAdminCard = dic["admin_id"][0].lower() message = ["", ""] if newAdminCard == oldAdminCard: message[0] = "You just introduced the old Admin Card." message[1] = "Please introduce a new Admin Card." defineAgain = True return render_template( "adminCardChanged.html", IP=str(Utils.settings["ownIpAddress"][0]), port=3000, adminCardChangeResult=message, defineAgain=defineAgain) else: Utils.settings["odooParameters"]["admin_id"] = dic[ "admin_id"] Utils.storeOptionInDeviceCustomization( "odooParameters", Utils.settings["odooParameters"]) message[0] = "The new Admin Card is " + dic["admin_id"][0] message[1] = "and was succesfully updated in Odoo." defineAgain = False exitFlag.set() # end all the threads return render_template( "adminCardChanged.html", IP=str(Utils.settings["ownIpAddress"][0]), port=3000, adminCardChangeResult=message, defineAgain=defineAgain) else: return render_template("reset_admin_form.html", IP=str(Utils.settings["ownIpAddress"][0]), port=3000) return srv
def _serve(self): # Load stored authentication keys self.refresh_keys() jsonify._instance = jsonify.GenericJSON( sort_keys=True, indent=4, separators=(',', ': '), ) server_addr = self.get_localized_config('server_addr', '::') if server_addr is None: raise CannotServe('no server_addr configured; try "ceph config-key set mgr/restful/server_addr <ip>"') server_port = int(self.get_localized_config('server_port', '8003')) self.log.info('server_addr: %s server_port: %d', server_addr, server_port) cert = self.get_localized_config("crt") if cert is not None: cert_tmp = tempfile.NamedTemporaryFile() cert_tmp.write(cert.encode('utf-8')) cert_tmp.flush() cert_fname = cert_tmp.name else: cert_fname = self.get_localized_config('crt_file') pkey = self.get_localized_config("key") if pkey is not None: pkey_tmp = tempfile.NamedTemporaryFile() pkey_tmp.write(pkey.encode('utf-8')) pkey_tmp.flush() pkey_fname = pkey_tmp.name else: pkey_fname = self.get_localized_config('key_file') if not cert_fname or not pkey_fname: raise CannotServe('no certificate configured') if not os.path.isfile(cert_fname): raise CannotServe('certificate %s does not exist' % cert_fname) if not os.path.isfile(pkey_fname): raise CannotServe('private key %s does not exist' % pkey_fname) # Publish the URI that others may use to access the service we're # about to start serving self.set_uri("https://{0}:{1}/".format( socket.gethostname() if server_addr == "::" else server_addr, server_port )) # Create the HTTPS werkzeug server serving pecan app self.server = make_server( host=server_addr, port=server_port, app=make_app( root='restful.api.Root', hooks = [ErrorHook()], # use a callable if pecan >= 0.3.2 ), ssl_context=(cert_fname, pkey_fname), ) self.server.serve_forever()
def __init__(self): super(ServerThread, self).__init__() self.srv = make_server("127.0.0.1", 5000, app) self.ctx = app.app_context() self.ctx.push()
@app.route('/current/daylight') def current_daylight_status(): return app.current_daylight_status() @app.route('/current/rain') def current_rain_status(): return app.current_rain_status() @app.route('/current/soil_moisture') def current_soil_moisture(): return app.current_soil_moisture() @app.route('/graph/temperature') def graph_temperature(): return app.graph_temperature() if __name__ == '__main__': # in debug mode start the server using flask built-in server # of course for production use mod-wsgi_express on Apache2 from werkzeug.serving import make_server # start on different port (production is 12000 to avoid conflicts) server = make_server('0.0.0.0', 12999, app) context = app.app_context() context.push() server.serve_forever()
def __init__(self, app): Thread.__init__(self) self.srv = make_server("127.0.0.1", 12000, app) self.ctx = app.app_context() self.ctx.push()
from werkzeug.serving import make_server from wsgi_benchmark.handlers import app if __name__ == '__main__': server = make_server('', 8765, app) server.serve_forever()
def run(self): app = Flask( __name__, static_url_path="", static_folder=get_resource("webclient_view", "webclient"), ) pl_event_queue = Queue() last_server_id = "" last_user_id = "" last_user_name = "" def wrap_playstate(active, playstate=None, item=None): if playstate is None: playstate = { "CanSeek": False, "IsPaused": False, "IsMuted": False, "RepeatMode": "RepeatNone", } res = { "PlayState": playstate, "AdditionalUsers": [], "Capabilities": { "PlayableMediaTypes": CAPABILITIES["PlayableMediaTypes"].split(","), "SupportedCommands": CAPABILITIES["SupportedCommands"].split(","), "SupportsMediaControl": True, "SupportsContentUploading": False, "SupportsPersistentIdentifier": False, "SupportsSync": False, }, "RemoteEndPoint": "0.0.0.0", "PlayableMediaTypes": CAPABILITIES["PlayableMediaTypes"].split(","), "Id": settings.client_uuid, "UserId": last_user_id, "UserName": last_user_name, "Client": USER_APP_NAME, "LastActivityDate": datetime.datetime.utcnow().isoformat(), "LastPlaybackCheckIn": "0001-01-01T00:00:00.0000000Z", "DeviceName": settings.player_name, "DeviceId": settings.client_uuid, "ApplicationVersion": CLIENT_VERSION, "IsActive": active, "SupportsMediaControl": True, "SupportsRemoteControl": True, "HasCustomDeviceName": False, "ServerId": last_server_id, "SupportedCommands": CAPABILITIES["SupportedCommands"].split(","), "dest": "player", } if "NowPlayingQueue" in playstate: res["NowPlayingQueue"] = playstate["NowPlayingQueue"] if "PlaylistItemId" in playstate: res["PlaylistItemId"] = playstate["PlaylistItemId"] if item: res["NowPlayingItem"] = item return res def on_playstate(state, payload=None, item=None): pl_event_queue.put(wrap_playstate(True, payload, item)) if state == "stopped": pl_event_queue.put(wrap_playstate(False)) def it_on_event(name, event): server_id = event["ServerId"] if type(event) is dict and "value" in event and len(event) == 2: event = event["value"] pl_event_queue.put({ "dest": "ws", "MessageType": name, "Data": event, "ServerId": server_id, }) playerManager.on_playstate = on_playstate eventHandler.it_on_event = it_on_event eventHandler.it_event_set = { "ActivityLogEntry", "LibraryChanged", "PackageInstallationCancelled", "PackageInstallationCompleted", "PackageInstallationFailed", "PackageInstalling", "RefreshProgress", "RestartRequired", "ScheduledTasksInfo", "SeriesTimerCancelled", "SeriesTimerCancelled", "SeriesTimerCreated", "SeriesTimerCreated", "ServerRestarting", "ServerShuttingDown", "Sessions", "TimerCancelled", "TimerCreated", "UserDataChanged", } @app.after_request def add_header(response): if request.path == "/index.html": do_not_cache(response) client_data = base64.b64encode( json.dumps({ "appName": USER_APP_NAME, "appVersion": CLIENT_VERSION, "deviceName": settings.player_name, "deviceId": settings.client_uuid, }).encode("ascii")) # We need access to this data before we can make an async web call. replacement = ( b"""<body><script type="application/json" id="clientData">%s</script>""" % client_data) if settings.desktop_scale != 1.0: f_scale = float(settings.desktop_scale) replacement = replacement + ( b"""<style>body { zoom: %.2f; }</style>""" % f_scale) response.make_sequence() response.set_data(response.get_data().replace( b"<body>", replacement, )) return response if not response.cache_control.no_store: response.cache_control.max_age = 2592000 return response @app.route("/mpv_shim_session", methods=["POST"]) def mpv_shim_session(): nonlocal last_server_id, last_user_id, last_user_name if request.headers[ "Content-Type"] != "application/json; charset=UTF-8": return "Go Away" req = request.json log.info("Recieved session for server: {0}, user: {1}".format( req["Name"], req["username"])) if req["Id"] not in clientManager.clients: is_logged_in = clientManager.connect_client(req) log.info("Connection was successful.") else: is_logged_in = True log.info("Ignoring as client already exists.") last_server_id = req["Id"] last_user_id = req["UserId"] last_user_name = req["username"] resp = jsonify({"success": is_logged_in}) resp.status_code = 200 if is_logged_in else 500 do_not_cache(resp) return resp @app.route("/mpv_shim_event", methods=["POST"]) def mpv_shim_event(): if request.headers[ "Content-Type"] != "application/json; charset=UTF-8": return "Go Away" try: queue_item = pl_event_queue.get(timeout=5) except Empty: queue_item = {} resp = jsonify(queue_item) resp.status_code = 200 do_not_cache(resp) return resp @app.route("/mpv_shim_message", methods=["POST"]) def mpv_shim_message(): if request.headers[ "Content-Type"] != "application/json; charset=UTF-8": return "Go Away" req = request.json client = clientManager.clients.get(req["payload"]["ServerId"]) resp = jsonify({}) resp.status_code = 200 do_not_cache(resp) if client is None: log.warning( "Message recieved but no client available. Ignoring.") return resp eventHandler.handle_event(client, req["name"], req["payload"], from_web=True) return resp @app.route("/mpv_shim_wsmessage", methods=["POST"]) def mpv_shim_wsmessage(): if request.headers[ "Content-Type"] != "application/json; charset=UTF-8": return "Go Away" req = request.json client = clientManager.clients.get(req["ServerId"]) resp = jsonify({}) resp.status_code = 200 do_not_cache(resp) if client is None: log.warning( "Message recieved but no client available. Ignoring.") return resp client.wsc.send(req["name"], req.get("payload", "")) return resp @app.route("/mpv_shim_teardown", methods=["POST"]) def mpv_shim_teardown(): if request.headers[ "Content-Type"] != "application/json; charset=UTF-8": return "Go Away" log.info("Client teardown requested.") clientManager.stop_all_clients() resp = jsonify({}) resp.status_code = 200 do_not_cache(resp) return resp @app.route("/mpv_shim_syncplay_join", methods=["POST"]) def mpv_shim_join(): if request.headers[ "Content-Type"] != "application/json; charset=UTF-8": return "Go Away" req = request.json client = list(clientManager.clients.values())[0] playerManager.syncplay.client = client playerManager.syncplay.join_group(req["GroupId"]) resp = jsonify({}) resp.status_code = 200 do_not_cache(resp) return resp self.srv = make_server("127.0.0.1", 18096, app, threaded=True) self.ctx = app.app_context() self.ctx.push() self.srv.serve_forever()
def __init__(self, app): threading.Thread.__init__(self) self.srv = make_server('0.0.0.0', CONFIG.APPLICATION.PORT, app) self.ctx = app.app_context() self.ctx.push()
def __init__(self, app): threading.Thread.__init__(self) self.srv = make_server("127.0.0.1", 9988, app) self.ctx = app.app_context() self.ctx.push()
def __init__(self, app): threading.Thread.__init__(self) self.srv = make_server(HOST, PORT, app) self.ctx = app.app_context() self.ctx.push()
def __init__(self, app, hostname="localhost", port=9000): super().__init__() self.hostname = hostname self.port = port self.server = make_server(self.hostname, self.port, app)
def startServerOdooParams(exitFlag): app = Flask("odoo_config_params") app.secret_key = os.urandom(12) Utils.getOwnIpAddress() srv = make_server(str(Utils.settings["ownIpAddress"][0]), 3000, app) ctx = app.app_context() ctx.push() server = ServerThread(srv) server.start() @app.route("/") def form(): if session.get("logged_in"): return render_template("form.html", IP=str(Utils.settings["ownIpAddress"][0]), port=3000, tz_dic=tz_sorted) else: return render_template("login.html") @app.route("/result", methods=["POST", "GET"]) def result(): #if request.method == "POST": results = request.form dic = results.to_dict(flat=False) Utils.storeOptionInDeviceCustomization("odooParameters", dic) exitFlag.set() # end all the threads return render_template("result.html", result=dic) #else: #return exitFlag.set() @app.route("/login", methods=["POST", "GET"]) def do_admin_login(): if request.method == "POST": if request.form.get("Reset credentials") == "Reset credentials": return render_template("change.html") elif request.form.get("Log in") == "Log in": #print("routes 190 - do_admin_login, credentialsDic ", Utils.settings["flask"]["new password"][0], ) if (request.form["password"] == Utils.settings["flask"] ["new password"][0]): session["logged_in"] = True else: flash("wrong password!") return form() else: return form() else: return form() @app.route("/change", methods=["POST", "GET"]) def change_credentials(): if request.method == "POST": result = request.form dataFromTheForm = result.to_dict(flat=False) if (str(dataFromTheForm["old password"][0]) == Utils.settings["flask"]["new password"][0]): Utils.storeOptionInDeviceCustomization("flask", dataFromTheForm) else: flash("wrong password!") return form() else: return form() return srv
def __init__(self, *args, **kwargs): self.host = kwargs.pop("host") self.port = kwargs.pop("port") threading.Thread.__init__(self, *args, **kwargs) self.server = make_server(self.host, self.port, app=app)
def __init__(self): threading.Thread.__init__(self) self.srv = make_server('127.0.0.1', FLASK_TEST_PORT, app) self.ctx = app.app_context() self.ctx.push()
def _mkserver(runner): from werkzeug.serving import make_server return make_server(self.host, self.port, self.mkwsgi(), threaded=self.threaded)
def __init__(self, app, port): threading.Thread.__init__(self, daemon=True) self.srv = make_server(host, port, app, True) self.ctx = app.app_context() self.ctx.push()
def make_simple_server(app, host, port): server = serving.make_server(host, port, app, threaded=True) server.daemon_threads = True server.handle_error = _handle_error tensorboard_url = "http://%s:%s" % (host, port) return server, tensorboard_url
def run(self): '''Start app''' self.server = make_server(self.address, self.port, self.app, threaded=True) self.server.serve_forever()
def _serve(self): # Load stored authentication keys self.refresh_keys() jsonify._instance = jsonify.GenericJSON( sort_keys=True, indent=4, separators=(',', ': '), ) server_addr = self.get_localized_module_option('server_addr', '::') if server_addr is None: raise CannotServe( 'no server_addr configured; try "ceph config-key set mgr/restful/server_addr <ip>"' ) server_port = int( self.get_localized_module_option('server_port', '8003')) self.log.info('server_addr: %s server_port: %d', server_addr, server_port) cert = self.get_localized_store("crt") if cert is not None: cert_tmp = tempfile.NamedTemporaryFile() cert_tmp.write(cert.encode('utf-8')) cert_tmp.flush() cert_fname = cert_tmp.name else: cert_fname = self.get_localized_store('crt_file') pkey = self.get_localized_store("key") if pkey is not None: pkey_tmp = tempfile.NamedTemporaryFile() pkey_tmp.write(pkey.encode('utf-8')) pkey_tmp.flush() pkey_fname = pkey_tmp.name else: pkey_fname = self.get_localized_module_option('key_file') self.enable_auth = self.get_localized_module_option( 'enable_auth', True) if not cert_fname or not pkey_fname: raise CannotServe('no certificate configured') if not os.path.isfile(cert_fname): raise CannotServe('certificate %s does not exist' % cert_fname) if not os.path.isfile(pkey_fname): raise CannotServe('private key %s does not exist' % pkey_fname) # Publish the URI that others may use to access the service we're # about to start serving self.set_uri("https://{0}:{1}/".format( self.get_mgr_ip() if server_addr == "::" else server_addr, server_port)) # Create the HTTPS werkzeug server serving pecan app self.server = make_server( host=server_addr, port=server_port, app=make_app( root='restful.api.Root', hooks=[ErrorHook()], # use a callable if pecan >= 0.3.2 ), ssl_context=(cert_fname, pkey_fname), ) sock_fd_flag = fcntl.fcntl(self.server.socket.fileno(), fcntl.F_GETFD) if not (sock_fd_flag & fcntl.FD_CLOEXEC): self.log.debug("set server socket close-on-exec") fcntl.fcntl(self.server.socket.fileno(), fcntl.F_SETFD, sock_fd_flag | fcntl.FD_CLOEXEC) if self.stop_server: self.log.debug('made server, but stop flag set') else: self.log.debug('made server, serving forever') self.server.serve_forever()
def rpc_server_worker(host, port, username, password, queue): dispatcher = Dispatcher() srv = None # prehash password password = int(sha256(bytes(password, "utf8")).hexdigest(), 16) @dispatcher.add_method def actions(args): try: actionlist = args[0] for action in actionlist: if action[0] not in ('mousemove', 'mousebutton', 'keyevent'): raise ValueError('unknown action') queue.put((None, 'actions', actionlist), True) return "OK" except: return "UNEXPECTED_INPUT" @dispatcher.add_method def mousebutton(args): respqueue = Queue(1) queue.put((respqueue, "mousebutton") + tuple(args), True) try: return respqueue.get(True, 5) except QueueEmpty: return "TIMEOUT" @dispatcher.add_method def mousemove(args): respqueue = Queue(1) queue.put((respqueue, "mousemove") + tuple(args), True) try: return respqueue.get(True, 5) except QueueEmpty: return "TIMEOUT" @dispatcher.add_method def keyevent(args): key, modifiers, down = args respqueue = Queue(1) queue.put((respqueue, "keyevent", key, modifiers or [], down), True) try: return respqueue.get(True, 5) except QueueEmpty: return "TIMEOUT" @dispatcher.add_method def devicecommand(args): devcommand = args respqueue = Queue(1) queue.put((respqueue, "devicecommand", devcommand), True) try: return respqueue.get(True, 5) except QueueEmpty: return "TIMEOUT" @dispatcher.add_method def exit(args): respqueue = Queue(1) queue.put((respqueue, "exit"), True) try: respqueue.get(True, 5) except: pass raise RPCServExitException() @Request.application def app(request): # auth with simplified version of equal op (timing attack secure) if (username != "" or password != "") and \ (getattr(request.authorization,"username","") != username or \ int(sha256(bytes(getattr(request.authorization,"password",""), "utf8")).hexdigest(), 16) - \ password != 0): json = JSONRPC20Response(error={ "code": 403, "message": "Invalid username or password!" }).json return Response(json, 403, mimetype='application/json') response = JSONRPCResponseManager.handle(request.data, dispatcher) return Response(response.json, mimetype='application/json') try: # response queue is used to notify result of attempt to run the server respqueue = queue.get() srv = make_server(host, port, app, request_handler=RequestHandler) logging.info("http-jsonrpc listening at {}:{}".format(host, port)) queue.task_done() # let run_rpc_server return respqueue.put("SUCCESS") srv.serve_forever() except RPCServExitException: logging.info("Exit exception raised!") except: queue.task_done() respqueue.put("FAIL") logging.error(traceback.format_exc())
def __init__(self, app, host, port): Thread.__init__(self) self.srv = make_server(host, port, app) self.ctx = app.app_context() self.ctx.push()
def __init__(self, app): threading.Thread.__init__(self) self.srv = make_server(str(get_ip()), 3000, app) self.ctx = app.app_context() self.ctx.push()
def run(self): app = Flask(__name__, static_url_path='', static_folder=get_resource("webclient_view", "webclient")) @app.after_request def add_header(response): if request.path == "/index.html": do_not_cache(response) if settings.desktop_scale != 1.0: f_scale = float(settings.desktop_scale) response.make_sequence() response.set_data(response.get_data().replace( b"</body>", b"""<style>body { zoom: %.2f; }</style></body>""" % f_scale )) return response if not response.cache_control.no_store: response.cache_control.max_age = 2592000 return response @app.route('/mpv_shim_password', methods=['POST']) def mpv_shim_password(): if request.headers['Content-Type'] != 'application/json; charset=UTF-8': return "Go Away" login_req = request.json success = clientManager.login(login_req["server"], login_req["username"], login_req["password"], True) if success: loaded.set() resp = jsonify({ "success": success }) resp.status_code = 200 do_not_cache(resp) return resp @app.route('/mpv_shim_id', methods=['POST']) def mpv_shim_id(): if request.headers['Content-Type'] != 'application/json; charset=UTF-8': return "Go Away" loaded.wait() resp = jsonify({ "appName": USER_APP_NAME, "deviceName": settings.player_name }) resp.status_code = 200 do_not_cache(resp) return resp @app.route('/mpv_shim_syncplay_join', methods=['POST']) def mpv_shim_join(): if request.headers['Content-Type'] != 'application/json; charset=UTF-8': return "Go Away" req = request.json client = list(clientManager.clients.values())[0] playerManager.syncplay.client = client playerManager.syncplay.join_group(req["GroupId"]) resp = jsonify({}) resp.status_code = 200 do_not_cache(resp) return resp @app.route('/destroy_session', methods=['POST']) def mpv_shim_destroy_session(): if request.headers['Content-Type'] != 'application/json; charset=UTF-8': return "Go Away" clientManager.remove_all_clients() resp = jsonify({ "success": True }) resp.status_code = 200 do_not_cache(resp) return resp self.srv = make_server('127.0.0.1', 18096, app, threaded=True) self.ctx = app.app_context() self.ctx.push() self.srv.serve_forever()
def __init__(self, app, address, port): threading.Thread.__init__(self) self.srv = make_server(address, port, app) self.ctx = app.app_context() self.ctx.push()
# command line arguments: # 1. the database name # 2. the user to connect as # 3. the file to create with the port number in it config = { 'postgresql': { 'dbnames': [sys.argv[1]], 'user': sys.argv[2] }, 'queries': { 'config': 'queries.yaml', 'template-path': 'queries', 'reload-templates': False } } tile_server = create_tileserver_from_config(config) tile_server.propagate_errors = True application = DebuggedApplication(tile_server, True) http_server = make_server('localhost', 0, application, threaded=False) with open(sys.argv[3] + ".tmp", 'w') as fh: print>>fh, "%d" % http_server.server_port # move into place atomically os.rename(sys.argv[3] + ".tmp", sys.argv[3]) http_server.serve_forever()
def __init__(self, app): threading.Thread.__init__(self) self.srv = make_server(str(get_ip()), 3000, app) self.ctx = app.app_context() self.ctx.push() _logger.debug("ServerThread Class Initialized")
def __init__(self, app: Flask, host: str, port: int): super().__init__() self._srv = make_server(host, port, app) self._ctx = app.app_context() self._ctx.push()
def __init__(self, app): threading.Thread.__init__(self) self.server = make_server('0.0.0.0', 5000, app) self.ctx = app.app_context() self.ctx.push()
def serve_forever(): make_server(hostname, port, application, processes=processes, threaded=threaded, passthrough_errors=passthrough_errors, ssl_context=ssl_context).serve_forever()
def run_simple(hostname, port, application, use_reloader=False, use_debugger=False, use_evalex=True, extra_files=None, reloader_interval=1, threaded=False, processes=1, request_handler=None, static_files=None, passthrough_errors=False, ssl_certificate="/etc/grid-security/hostcert.pem", ssl_key="/etc/grid-security/hostkey.pem", ssl_ca_path="/etc/grid-security/certificates", backend_port=None, stud_executable=None ): """Start an application using wsgiref and with an optional reloader. This wraps `wsgiref` to fix the wrong default reporting of the multithreaded WSGI variable and adds optional multithreading and fork support. :param hostname: The host for the application. eg: ``'localhost'`` :param port: The port for the server. eg: ``8080`` :param application: the WSGI application to execute :param use_reloader: should the server automatically restart the python process if modules were changed? :param use_debugger: should the werkzeug debugging system be used? :param use_evalex: should the exception evaluation feature be enabled? :param extra_files: a list of files the reloader should watch additionally to the modules. For example configuration files. :param reloader_interval: the interval for the reloader in seconds. :param threaded: should the process handle each request in a separate thread? :param processes: number of processes to spawn. :param request_handler: optional parameter that can be used to replace the default one. You can use this to replace it with a different :class:`~BaseHTTPServer.BaseHTTPRequestHandler` subclass. :param static_files: a dict of paths for static files. This works exactly like :class:`SharedDataMiddleware`, it's actually just wrapping the application in that middleware before serving. :param passthrough_errors: set this to `True` to disable the error catching. This means that the server will die on errors but it can be useful to hook debuggers in (pdb etc.) :param ssl_certificate: path to the host SSL certificate. Default is /etc/grid-security/hostcert.pem :param ssl_key: path to the host SSL key. Default is /etc/grid-security/hostkey.pem :param ssl_ca_path: path to the accepted CA certificates directory. Default is /etc/grid-security/certificates :param backend_port: port for plain HTTP backend. Will be chosen automatically if not specified. :param stud_executable: path to stud executable. If not specified will search for stud executable in standard package locations and $PATH. """ if use_debugger: from werkzeug.debug import DebuggedApplication application = DebuggedApplication(application, use_evalex) if static_files: from werkzeug.wsgi import SharedDataMiddleware application = SharedDataMiddleware(application, static_files) hmac_key = make_hmac_key() if backend_port is None: backend_port = find_free_port() stud_executable = get_stud_executable(stud_executable) if not stud_executable: raise RuntimeError("Can't find stud executable. Please specify correct path in stud_executable") fd, keycertfile = mkstemp() f = os.fdopen(fd, "wb") shutil.copyfileobj(open(ssl_certificate, "rb"), f) shutil.copyfileobj(open(ssl_key, "rb"), f) f.close() atexit.register(remove_keycertfile, keycertfile) stud_pid = start_stud(stud_executable, port, backend_port, hmac_key, ssl_ca_path, keycertfile) atexit.register(os.kill, stud_pid, 15) from werkzeug._internal import _log display_hostname = hostname != '*' and hostname or 'localhost' if ':' in display_hostname: display_hostname = '[%s]' % display_hostname _log('info', ' * Frontend running on https://%s:%d/', display_hostname, port) _log('info', ' * Backend running on http://127.0.0.1:%d/', backend_port) make_server(hostname, backend_port, application, threaded, processes, request_handler, passthrough_errors).serve_forever()
def serve_error_app(tb_str, monitored_files): from clastic import flaw err_app = flaw.create_app(tb_str, monitored_files) err_server = make_server(hostname, port, err_app) thread.start_new_thread(err_server.serve_forever, ()) return err_server
def make_simple_server(tb_app, host=None, port=None, path_prefix=None): """Create an HTTP server for TensorBoard. Args: tb_app: The TensorBoard WSGI application to create a server for. host: Indicates the interfaces to bind to ('::' or '0.0.0.0' for all interfaces, '::1' or '127.0.0.1' for localhost). A blank value ('') indicates protocol-agnostic all interfaces. If not specified, will default to the flag value. port: The port to bind to (0 indicates an unused port selected by the operating system). If not specified, will default to the flag value. path_prefix: Optional relative prefix to the path, e.g. "/service/tf" Returns: A tuple of (server, url): server: An HTTP server object configured to host TensorBoard. url: A best guess at a URL where TensorBoard will be accessible once the server has been started. Raises: socket.error: If a server could not be constructed with the host and port specified. Also logs an error message. """ if host is None: host = FLAGS.host if port is None: port = FLAGS.port if path_prefix is None: path_prefix = FLAGS.path_prefix try: if host: # The user gave us an explicit host server = serving.make_server(host, port, tb_app, threaded=True) if ':' in host and not host.startswith('['): # Display IPv6 addresses as [::1]:80 rather than ::1:80 final_host = '[{}]'.format(host) else: final_host = host else: # We've promised to bind to all interfaces on this host. However, we're # not sure whether that means IPv4 or IPv6 interfaces. try: # First try passing in a blank host (meaning all interfaces). This, # unfortunately, defaults to IPv4 even if no IPv4 interface is available # (yielding a socket.error). server = serving.make_server(host, port, tb_app, threaded=True) except socket.error: # If a blank host didn't work, we explicitly request IPv6 interfaces. server = serving.make_server('::', port, tb_app, threaded=True) final_host = socket.gethostname() server.daemon_threads = True except socket.error: if port == 0: msg = 'TensorBoard unable to find any open port' else: msg = ( 'TensorBoard attempted to bind to port %d, but it was already in use' % port) tf.logging.error(msg) print(msg) raise server.handle_error = _handle_error final_port = server.socket.getsockname()[1] tensorboard_url = 'http://%s:%d%s' % (final_host, final_port, path_prefix) return server, tensorboard_url
def inner(): self.server = make_server(hostname, port, application) self.server.serve_forever()