PORT = 5000 # The same port as used by the server app_s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) app_s.connect((HOST, PORT)) if request.environ.get('wsgi.websocket'): web_s = request.environ['wsgi.websocket'] while True: #メインプログラムからの通信 data = app_s.recv(1024) print "recive:" + data name = data.split(":")[0] msg = data.split(":")[1] send_data = {"name": name, "message": msg} web_s.send(json.dumps(send_data)) #webからの通信 #result = web_s.receive()##unicode文字列が入る #print result #app_s.send(result) return if __name__ == '__main__': app.debug = True server = pywsgi.WSGIServer(('127.0.0.1', 8000), app, handler_class=WebSocketHandler) server.serve_forever()
log_session['logplex_url'], headers=headers, auth=auth, stream=True ) def generate(): for line in log.iter_lines(): if line: decoded_line = line.decode('utf-8') yield decoded_line + '\n' return Response(generate(), mimetype='text/plain') sched = BackgroundScheduler() if os.getenv('DISABLE_WORKER') != 'true': sched.add_job(check_pull_requests, 'interval', minutes=51) sched.start() app.secret_key = os.getenv('SESSION_SECRET') app.debug = os.getenv('DEBUG', 'false').lower() == 'true' if __name__ == '__main__': # app.run(host='0.0.0.0', port=int(os.getenv("PORT", 5001))) from gevent import pywsgi from geventwebsocket.handler import WebSocketHandler server = pywsgi.WSGIServer(('', 5000), app, handler_class=WebSocketHandler) server.serve_forever()
def startWebsocket(): from gevent import pywsgi from geventwebsocket.handler import WebSocketHandler server = pywsgi.WSGIServer(('', websocket_port), app, handler_class=WebSocketHandler) server.serve_forever()
def init_server(self, application): self.server = pywsgi.WSGIServer(('127.0.0.1', 0), application, certfile=self.certfile, keyfile=self.keyfile)
def start_server(): app.secret_key = os.urandom(24) print("SERVER STARTED") port = int(os.environ.get('PORT', 5000)) pywsgi.WSGIServer(('0.0.0.0', port), app).serve_forever()
def run(self, app, host=None, port=None, **kwargs): """Run the SocketIO web server. :param app: The Flask application instance. :param host: The hostname or IP address for the server to listen on. Defaults to 127.0.0.1. :param port: The port number for the server to listen on. Defaults to 5000. :param debug: ``True`` to start the server in debug mode, ``False`` to start in normal mode. :param use_reloader: ``True`` to enable the Flask reloader, ``False`` to disable it. :param extra_files: A list of additional files that the Flask reloader should watch. Defaults to ``None`` :param log_output: If ``True``, the server logs all incomming connections. If ``False`` logging is disabled. Defaults to ``True`` in debug mode, ``False`` in normal mode. Unused when the threading async mode is used. :param kwargs: Additional web server options. The web server options are specific to the server used in each of the supported async modes. Note that options provided here will not be seen when using an external web server such as gunicorn, since this method is not called in that case. """ if host is None: host = '127.0.0.1' if port is None: server_name = app.config['SERVER_NAME'] if server_name and ':' in server_name: port = int(server_name.rsplit(':', 1)[1]) else: port = 5000 debug = kwargs.pop('debug', app.debug) log_output = kwargs.pop('log_output', debug) use_reloader = kwargs.pop('use_reloader', debug) extra_files = kwargs.pop('extra_files', None) app.debug = debug if app.debug and self.server.eio.async_mode != 'threading': # put the debug middleware between the SocketIO middleware # and the Flask application instance # # mw1 mw2 mw3 Flask app # o ---- o ---- o ---- o # / # o Flask-SocketIO # \ middleware # o # Flask-SocketIO WebSocket handler # # BECOMES # # dbg-mw mw1 mw2 mw3 Flask app # o ---- o ---- o ---- o ---- o # / # o Flask-SocketIO # \ middleware # o # Flask-SocketIO WebSocket handler # self.sockio_mw.wsgi_app = DebuggedApplication(self.sockio_mw.wsgi_app, evalex=True) if self.server.eio.async_mode == 'threading': from werkzeug._internal import _log _log('warning', 'WebSocket transport not available. Install ' 'eventlet or gevent and gevent-websocket for ' 'improved performance.') app.run(host=host, port=port, threaded=True, use_reloader=use_reloader, **kwargs) elif self.server.eio.async_mode == 'eventlet': def run_server(): import eventlet eventlet_socket = eventlet.listen((host, port)) # If provided an SSL argument, use an SSL socket ssl_args = ['keyfile', 'certfile', 'server_side', 'cert_reqs', 'ssl_version', 'ca_certs', 'do_handshake_on_connect', 'suppress_ragged_eofs', 'ciphers'] ssl_params = {k: kwargs[k] for k in kwargs if k in ssl_args} if len(ssl_params) > 0: for k in ssl_params: kwargs.pop(k) ssl_params['server_side'] = True # Listening requires true eventlet_socket = eventlet.wrap_ssl(eventlet_socket, **ssl_params) eventlet.wsgi.server(eventlet_socket, app, log_output=log_output, **kwargs) if use_reloader: run_with_reloader(run_server, extra_files=extra_files) else: run_server() elif self.server.eio.async_mode == 'gevent': from gevent import pywsgi try: from geventwebsocket.handler import WebSocketHandler websocket = True except ImportError: websocket = False log = 'default' if not log_output: log = None if websocket: self.wsgi_server = pywsgi.WSGIServer( (host, port), app, handler_class=WebSocketHandler, log=log, **kwargs) else: self.wsgi_server = pywsgi.WSGIServer((host, port), app, log=log) if use_reloader: # monkey patching is required by the reloader from gevent import monkey monkey.patch_all() def run_server(): self.wsgi_server.serve_forever() run_with_reloader(run_server, extra_files=extra_files) else: self.wsgi_server.serve_forever()
def init_server(self, application): self.server = pywsgi.WSGIServer(('127.0.0.1', 0), application, handler_class=Handler)
def run(self): # Setup all of the robot management functions # TODO some of these should probably be POST methods... robot_flask = flask.Flask(__name__) @robot_flask.route('/', methods=['GET']) def __hello(): return flask.jsonify("Hello, I am the BenchBot robot controller") @robot_flask.route('/config/', methods=['GET']) def __config_full(): return flask.jsonify(self.config) @robot_flask.route('/config/<config>', methods=['GET']) def __config(config): if config in self.config: return flask.jsonify(self.config[config]) else: rospy.logerr("Requested non-existent config: %s" % config) flask.abort(404) @robot_flask.route('/configure', methods=['POST']) def __configure(): try: self.set_config(flask.request.json) except Exception as e: print(traceback.format_exc()) raise (e) return flask.jsonify({'configuration_valid': self.config_valid}) @robot_flask.route('/connections/<connection>', methods=['GET', 'POST']) def __connection(connection): # Handle all connection calls (typically sent via the supervisor) if connection not in self.config['robot']['connections']: rospy.logerr("Requested undefined connection: %s" % connection) flask.abort(404) try: return flask.jsonify( jsonpickle.encode( self._call_connection(connection, data=flask.request.get_json()))) except Exception as e: rospy.logerr( "Robot Controller failed on processing connection " "'%s' with error:\n%s\n%s" % (connection, repr(e), traceback.format_exc())) flask.abort(500) @robot_flask.route('/is_collided', methods=['GET']) def __is_collided(): return flask.jsonify({'is_collided': self.instance.is_collided()}) @robot_flask.route('/is_dirty', methods=['GET']) def __is_dirty(): return flask.jsonify({'is_dirty': self.instance.is_dirty()}) @robot_flask.route('/is_finished', methods=['GET']) def __is_finished(): return flask.jsonify({ 'is_finished': (False if 'trajectory_pose_next' not in self.state else self.state['trajectory_pose_next'] >= len( self.state['trajectory_poses'])) }) @robot_flask.route('/is_running', methods=['GET']) def __is_running(): try: return flask.jsonify( {'is_running': self.instance.is_running()}) except Exception as e: rospy.logerr(e) @robot_flask.route('/next', methods=['GET']) def __next(): try: if self._env_next() == 0: raise ValueError( "There is no next map; at the end of the list") self.stop() self.state['selected_environment'] = self._env_next() self.start() success = True except Exception as e: rospy.logerr(e) success = False return flask.jsonify({'next_success': success}) @robot_flask.route('/reset', methods=['GET']) def __reset(): # Resets the robot in the current scene try: self.restart() success = self.instance.is_running() except Exception as e: rospy.logerr(e) success = False return flask.jsonify({'reset_success': success}) @robot_flask.route('/restart', methods=['GET']) def __restart(): # Restarts the robot in the FIRST scene self.wipe() resp = __reset() resp.data = resp.data.replace('reset', 'restart') return resp @robot_flask.route('/selected_environment', methods=['GET']) def __selected_env(): try: return flask.jsonify({ 'name': self.config['environments'][ self.state['selected_environment']]['name'], 'variant': self.config['environments'][ self.state['selected_environment']]['variant'], 'number': self.state['selected_environment'] }) except Exception as e: rospy.logerr(e) # Configure our server robot_server = pywsgi.WSGIServer( re.split('http[s]?://', self.robot_address)[-1], robot_flask) evt = event.Event() signal.signal(signal.SIGINT, evt.set) signal.signal(signal.SIGQUIT, evt.set) signal.signal(signal.SIGTERM, evt.set) # Run the server & start the real robot controller robot_server.start() print("\nRobot controller is now available @ '%s' ..." % self.robot_address) print("Waiting to receive valid config data...") while not self.config_valid: if evt.wait(0.1): break if self._auto_start and self.config_valid: print("Starting the requested real robot ROS stack ... ", end="") sys.stdout.flush() self.start() print("Done") # Wait until we get an exit signal or crash, then shut down gracefully while self.instance.health_check(): if evt.wait(0.1): break print("\nShutting down the real robot ROS stack & exiting ...") robot_server.stop() self.stop() print("Stopped")
{ "content": search_result, } ] result = render_template('tmpl_search.html', title="口红色号查询 ;)", ver=app_ver, update_date=update_date, data=data_list) except Exception as e: result = None logger.error(msg="[MLS_WEB] " + repr(e)) logger.debug(msg="------Traceback------\n" + tb.format_exc()) if result is None: result = render_template('tmpl_search_null.html', ver=app_ver, update_date=update_date) return result # 测试获取预测结果 # test_result = get_search_result("#DE4A3C") # print(test_result) # 测试url获取数据(复制粘贴到浏览器地址栏并访问) # url: http://127.0.0.1:9992/search?kw=%2523B03C79 # server server = pywsgi.WSGIServer(('0.0.0.0', 9992), flask_app) # wsgi # server = pywsgi.WSGIServer(('127.0.0.1', 9992), flask_app) # wsgi localhost debug server.serve_forever() # flask_app.run(host='0.0.0.0', port=9992, debug=True) # flask默认运行方式,带debug开关
@eio.on('disconnect') def disconnect(sid): print('disconnect ', sid) if __name__ == '__main__': if async_mode == 'threading': # deploy with Werkzeug app.run(threaded=True) elif async_mode == 'eventlet': # deploy with eventlet import eventlet from eventlet import wsgi wsgi.server(eventlet.listen(('', 5000)), app) elif async_mode == 'gevent': # deploy with gevent from gevent import pywsgi try: from geventwebsocket.handler import WebSocketHandler websocket = True except ImportError: websocket = False if websocket: pywsgi.WSGIServer(('', 5000), app, handler_class=WebSocketHandler).serve_forever() else: pywsgi.WSGIServer(('', 5000), app).serve_forever() else: print('Unknown async_mode: ' + async_mode)
def start(locust, options): pywsgi.WSGIServer((options.web_host, options.port), app, log=None).serve_forever()
import os monkey.patch_all() from chat import hub, route async_mode = 'gevent' PORT = int(os.environ.get('PORT', 3000)) SECRET_KEY = os.environ.get('SECRET_KEY', 'schwanfc') PEER = os.environ.get('PEER', 'false').lower() == 'true' if PEER: print('Running in peer mode!') mgr = socketio.RedisManager('redis://') sio = socketio.Server(client_manager=mgr, logger=True, async_mode=async_mode) else: sio = socketio.Server(logger=True, async_mode=async_mode) app = Flask(__name__) app.wsgi_app = socketio.WSGIApp(sio, app.wsgi_app) app.config['SECRET_KEY'] = SECRET_KEY hub.init(sio) route.init(app) if __name__ == '__main__': print(f'Server is running on port {PORT}') pywsgi.WSGIServer(('', PORT), app, handler_class=WebSocketHandler).serve_forever()
def run(self): log = None if self.config.test else 'default' server = pywsgi.WSGIServer((self.hostname, self.port), self.app, log=log) server.serve_forever()
#!/usr/bin/python """Secure WSGI server example based on gevent.pywsgi""" from __future__ import print_function from gevent import pywsgi def hello_world(env, start_response): if env['PATH_INFO'] == '/': start_response('200 OK', [('Content-Type', 'text/html')]) return [b"<b>hello world</b>"] else: start_response('404 Not Found', [('Content-Type', 'text/html')]) return [b'<h1>Not Found</h1>'] print('Serving on https://:8443') server = pywsgi.WSGIServer(('', 8443), hello_world, keyfile='server.key', certfile='server.crt') # to start the server asynchronously, call server.start() # we use blocking serve_forever() here because we have no other jobs server.serve_forever()
def RunServer(): server = pywsgi.WSGIServer(('127.0.0.1', 5000), app, handler_class=WebSocketHandler) print("Server Started!") server.serve_forever()
t_user.id == i.user_id).first().username i.uptime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(i.update_time)) i.uppro = u'未上线' return render_template('build.html', db_logs=db_logs, html_page='proshenji.html') else: return redirect('/login.html') @app.route('/<fileurl>.html') def viewhtml(fileurl): return render_template(fileurl + '.html', services=ArgInput.all_arg) @app.route('/admin/<fileurl>.html') def renzhen(fileurl): if session['group_id'] == 1: return render_template('admin/' + fileurl + '.html') else: return render_template('error.html') if __name__ == '__main__': server = pywsgi.WSGIServer(('0.0.0.0', 9080), app) server.serve_forever()
from calendar_config import app from views.calendar.pub_calendar import pub_calendar from views.calendar.user_calendar import user_calendar from views.public_auth import auth from views.public_pub import calendar_pub_view from gevent import pywsgi app.register_blueprint(auth) # 用户相关 app.register_blueprint(calendar_pub_view) # 公用 app.register_blueprint(pub_calendar) # 公用日历 app.register_blueprint(user_calendar) # 个人日历 if __name__ == '__main__': # app.run(host="0.0.0.0", port=5000, debug=True) server = pywsgi.WSGIServer(("0.0.0.0", 5004), app) # 启动ip和端口 server.serve_forever() # 监听
from application import create_app app = create_app() if __name__ == '__main__': from gevent import pywsgi from geventwebsocket.handler import WebSocketHandler print('Open in browser - 0.0.0.0:8080') server = pywsgi.WSGIServer(('0.0.0.0', 8080), app, handler_class=WebSocketHandler) server.serve_forever()
elif args.mode == 'faucet': while 1: Peers.init(config, mongo, args.network) if not Peers.peers: time.sleep(1) continue Faucet.run(config, mongo) time.sleep(1) elif args.mode == 'pool': pp = PoolPayer(config, mongo) while 1: pp.do_payout() time.sleep(1) elif args.mode == 'serve': print config.to_json() config.network = args.network my_peer = Peer.init_my_peer(config, mongo, config.network) config.callbackurl = 'http://%s/create-relationship' % my_peer.to_string( ) print "http://{}".format(my_peer.to_string()) serve = Serve(config, mongo) pywsgi.WSGIServer((config.serve_host, config.serve_port), serve.app, spawn=pool.Pool(100)).serve_forever()
def run(self, handler): server = pywsgi.WSGIServer((self.host, self.port), handler, handler_class=WebSocketHandler) server.serve_forever()
def init_server(self, application): self.server = pywsgi.WSGIServer(('127.0.0.1', 0), application)
from gevent import pywsgi from vvip_video.wsgi import application server = pywsgi.WSGIServer(('0.0.0.0', 8000), application) application.debug = True server.serve_forever()
@app.route('/pipe') def pipe(): # websocket接続要求 if request.environ.get('wsgi.websocket'): # websocket生成 ws = request.environ['wsgi.websocket'] while True: # logファイル読み込み with open(os.path.dirname(os.path.abspath(__file__)) +'/logs/' + 'logging'+'.log', "rU") as f: data = f.read() try: ws.send(data) except Exception: return 'Error:WebSockeが切断されました。', 400 if __name__ == '__main__': server = pywsgi.WSGIServer(("0.0.0.0", 8000), app, handler_class=WebSocketHandler) server.serve_forever()
def run(): server = pywsgi.WSGIServer( ('0.0.0.0', int(port)), app, handler_class=WebSocketHandler) server.serve_forever()
@app.route('/', methods=['GET']) def index(): '''do nothing here''' if request.method == 'GET': return 'local service alarm{}'.format(__version__) @app.route("/alarm", methods=['POST']) def alarm(): if request.method == 'POST': if request.json is None: return "interface error : missing parameters" try: title = request.json['title'] content = request.json['content'] ring(title, content) return f"call successfully" except KeyError as e: return f"interface error : missing parameter:{e}" if __name__ == "__main__": ring('MicroServicev1.1', '全局闹钟已经启动...') gserver = pywsgi.WSGIServer(("localhost", 8688), app) gserver.serve_forever()
""" Production entry point that launches the gevent WSGI server in place of Flask's default one. The workload for this service is entirely I/O bound, so should improve the service's ability to handle more concurrent connections without using a multi-process WSGI server like `gunicorn`. """ from gevent import monkey, pywsgi monkey.patch_all() import kubernetes # noqa: E402 from allennlp_demo.info.api import InfoService # noqa: E402 if __name__ == "__main__": kubernetes.config.load_incluster_config() app = InfoService() # Note, we set `log=None` to disable the `gevent` request log in favor # of ours which includes the info we want. server = pywsgi.WSGIServer(("0.0.0.0", 8000), app, log=None, error_log=app.logger) server.serve_forever()
# If using a Gateway URL start the connection if args.gateway_url is not None: if "http://" in args.host: node_address = "{}:{}".format(args.host, args.port) else: node_address = "http://{}:{}".format(args.host, args.port) requests.post( os.path.join(args.gateway_url, "join"), data=json.dumps({ "node-id": args.id, "node-address": node_address }), ) server = pywsgi.WSGIServer(("", args.port), app, handler_class=WebSocketHandler) server.serve_forever() else: ## DEPLOYMENT MODE (we use gunicorn's worker to perform load balancing) # These environment variables must be set before starting the application. gateway_url = os.environ.get("GRID_NETWORK_URL", None) node_id = os.environ.get("ID", None) node_address = os.environ.get("ADDRESS", None) # If using a Gateway URL start the connection if gateway_url: requests.post( os.path.join(gateway_url, "join"), data=json.dumps({
def run(flask: Flask) -> None: server = pywsgi.WSGIServer(('', 8080), flask, handler_class=WebSocketHandler) server.serve_forever() flask.run(port=8080)
#!/usr/bin/env python import json import random from gevent import pywsgi, sleep from geventwebsocket.handler import WebSocketHandler class WebSocketApp(object): '''Send random data to the websocket''' def __call__(self, environ, start_response): ws = environ['wsgi.websocket'] x = 0 while True: data = json.dumps({'x': x, 'y': random.randint(1, 5)}) ws.send(data) x += 1 sleep(0.5) server = pywsgi.WSGIServer(("", 10000), WebSocketApp(), handler_class=WebSocketHandler) server.serve_forever()
if json['message'].encode().decode('utf8', 'replace').replace( '<', '<') != "": #Если в Json есть собщение, то data = { 'id': json['id'].encode().decode('utf8', 'replace'), #Исправляем кодировку 'message': json['message'].encode().decode('utf8', 'replace').replace('<', '<') } #Заменяем знак '<' на спецсимвол для защиты от html разметки print(json['id'].encode().decode('utf8', 'replace') + json['message'].encode().decode('utf8', 'replace').replace( '<', '<')) socketio.emit('my response', data) #Отправляем сообщение в браузер if streamer: # Если есть стример, то streamer[0].send( json['id'].encode().decode('utf8', 'replace') + json['message'].encode().decode('utf8', 'replace').replace( '<', '<')) #Отправляем QT стримеру сообщение if __name__ == "__main__": global streamer #Глобальная переменная стримера streamer = [] # Лист для сокета from gevent import pywsgi from geventwebsocket.handler import WebSocketHandler server = pywsgi.WSGIServer( ('0.0.0.0', 5000), app, handler_class=WebSocketHandler) #Настройка сервера server.serve_forever() #Запуск сервера