Python flask_socketio.SocketIO() Examples

The following are 18 code examples of flask_socketio.SocketIO(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask_socketio , or try the search function .
Example #1
Source File: event_stream.py    From zou with GNU Affero General Public License v3.0 6 votes vote down vote up
def create_app(redis_url):
    socketio = SocketIO(logger=True)

    app = Flask(__name__)
    app.config.from_object(config)

    @app.route("/")
    def index():
        return jsonify({"name": "%s Event stream" % config.APP_NAME})

    @socketio.on("connect", namespace="/events")
    def connected():
        try:
            verify_jwt_in_request()
            app.logger.info("New websocket client connected")
        except Exception:
            app.logger.info("New websocket client failed to connect")
            disconnect()
            return False

    @socketio.on("disconnect", namespace="/events")
    def disconnected():
        app.logger.info("Websocket client disconnected")

    @socketio.on_error("/events")
    def on_error(error):
        app.logger.error(error)

    socketio.init_app(app, message_queue=redis_url, async_mode="gevent")
    return (app, socketio) 
Example #2
Source File: publisher_store.py    From zou with GNU Affero General Public License v3.0 6 votes vote down vote up
def init():
    """
    Initialize key value store that will be used for the event publishing.
    That way the main API takes advantage of Redis pub/sub capabilities to push
    events to the event stream API.
    """
    global socketio

    try:
        publisher_store = redis.StrictRedis(
            host=host, port=port, db=redis_db, decode_responses=True
        )
        publisher_store.get("test")
        socketio = SocketIO(message_queue=redis_url)
    except redis.ConnectionError:
        pass

    return socketio 
Example #3
Source File: dashboard.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def main(config):
    config.restricted_to = None  # allow access to the whole config file
    plot_cache = cea.plots.cache.MemoryPlotCache(config.project)
    app = Flask(__name__, static_folder='base/static')
    app.config.from_mapping({'SECRET_KEY': 'secret'})

    global socketio
    socketio = SocketIO(app)

    import plots.routes
    from server import blueprint as server_blueprint
    from api import blueprint as api_blueprint
    app.register_blueprint(plots.routes.blueprint)
    app.register_blueprint(api_blueprint)
    app.register_blueprint(server_blueprint)

    # keep a copy of the configuration we're using
    app.cea_config = config
    app.plot_cache = plot_cache
    app.socketio = socketio

    print("start socketio.run")
    socketio.run(app, host='localhost', port=5050)
    print("done socketio.run") 
Example #4
Source File: dashboard.py    From kryptoflow with GNU General Public License v3.0 6 votes vote down vote up
def create_app(cls, env):
        app = Flask(__name__,
                    static_folder=cls.static_files_dir,
                    template_folder=cls.react_dist_dir)

        CORS(app, resources={r"/*": {"origins": "*"}})
        socketio = SocketIO(app)
        app.config.from_object(config_by_name[env])
        app.register_blueprint(api_bp, url_prefix='/api/v1')

        @app.route('/')
        def index():
            return send_from_directory(cls.static_files_dir, "index.html")

        @app.route('/<path:path>')
        def catch_all(path):
            return send_from_directory(cls.react_dist_dir, "index.html")

        return app 
Example #5
Source File: __init__.py    From OpenPoGoBot with MIT License 6 votes vote down vote up
def run_socket_server(self):
        app = Flask(__name__)
        app.config["SECRET_KEY"] = "OpenPoGoBotSocket"
        socketio = SocketIO(app, logging=False, engineio_logger=False, json=myjson)

        @app.route("/")
        def redirect_online():
            return redirect("http://openpogoui.nicontoso.eu")

        state = {}

        BotEvents(self.bot, socketio, state, self.event_manager)
        UiEvents(self.bot, socketio, state, self.event_manager, self.logger)

        self.log("Starting socket server...")

        socketio.run(
            app,
            host=self.config['socket_server']['host'] or '0.0.0.0',
            port=self.config['socket_server']['port'] or 8080,
            debug=False,
            use_reloader=False,
            log_output=False
        ) 
Example #6
Source File: __init__.py    From betterlifepsi with MIT License 5 votes vote down vote up
def init_socket_io(app):
    from flask_socketio import SocketIO
    from psi.app.socketio import init_socket_tio_handlers
    socket_io = SocketIO(app)
    init_socket_tio_handlers(socket_io)
    return socket_io 
Example #7
Source File: app_socket.py    From docassemble with MIT License 5 votes vote down vote up
def create_app():
    app = Flask(__name__)
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    from docassemble.base.config import daconfig
    import docassemble.webapp.database
    connect_string = docassemble.webapp.database.connection_string()
    alchemy_connect_string = docassemble.webapp.database.alchemy_connection_string()
    #app.config['SQLALCHEMY_DATABASE_URI'] = alchemy_connect_string
    app.secret_key = daconfig.get('secretkey', '38ihfiFehfoU34mcq_4clirglw3g4o87')
    #app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    #db = SQLAlchemy(app)
    db = sqlalchemy.create_engine(alchemy_connect_string, pool_pre_ping=docassemble.webapp.database.pool_pre_ping)
    Base = declarative_base()
    Base.metadata.bind = db
    #app.wsgi_app = ProxyFix(app.wsgi_app)
    db.Model = Base
    db.Column = sqlalchemy.Column
    db.Integer = sqlalchemy.Integer
    db.String = sqlalchemy.String
    db.Index = sqlalchemy.Index
    db.Boolean = sqlalchemy.Boolean
    db.Text = sqlalchemy.Text
    db.DateTime = sqlalchemy.DateTime
    db.func = sqlalchemy.func
    db.relationship = relationship
    db.backref = backref
    db.ForeignKey = sqlalchemy.ForeignKey
    docassemble.webapp.db_object.db = db
    #import flask_login
    docassemble.webapp.db_object.UserMixin = object
    socketio = SocketIO(app, async_mode='eventlet', verify=False, logger=True, engineio_logger=True, cors_allowed_origins=[daconfig.get('url root', '*')])
    return app, db, socketio 
Example #8
Source File: api_server.py    From kytos with MIT License 5 votes vote down vote up
def __init__(self, app_name, listen='0.0.0.0', port=8181,
                 napps_manager=None, napps_dir=None):
        """Start a Flask+SocketIO server.

        Require controller to get NApps dir and NAppsManager

        Args:
            app_name(string): String representing a App Name
            listen (string): host name used by api server instance
            port (int): Port number used by api server instance
            controller(kytos.core.controller): A controller instance.
        """
        dirname = os.path.dirname(os.path.abspath(__file__))
        self.napps_manager = napps_manager
        self.napps_dir = napps_dir

        self.flask_dir = os.path.join(dirname, '../web-ui')
        self.log = logging.getLogger(__name__)

        self.listen = listen
        self.port = port

        self.app = Flask(app_name, root_path=self.flask_dir,
                         static_folder="dist", static_url_path="/dist")
        self.server = SocketIO(self.app, async_mode='threading')
        self._enable_websocket_rooms()
        # ENABLE CROSS ORIGIN RESOURCE SHARING
        CORS(self.app)

        # Disable trailing slash
        self.app.url_map.strict_slashes = False

        # Update web-ui if necessary
        self.update_web_ui(force=False) 
Example #9
Source File: server.py    From watson-online-store with Apache License 2.0 5 votes vote down vote up
def do_connect():
    """On web UI connect, do something here."""
    # On web UI connect, send a generic greeting via Flask SocketIO.
    # Uncomment for debugging. Not great for normal use case.
    # emit('my_response', {'data': 'Hello!'})
    pass 
Example #10
Source File: server.py    From watson-online-store with Apache License 2.0 5 votes vote down vote up
def send_message(self, message):
        """Function to send a message to the web-ui via Flask SocketIO."""
        lines = message.split('\n')
        for line in lines:
            image = None
            if 'output_format[png]' in line:
                line, http_tail = line.split('http', 1)
                image = 'http' + http_tail

            emit('my_response', {'data': line.strip(), 'image': image}) 
Example #11
Source File: web.py    From dino with Apache License 2.0 5 votes vote down vote up
def create_app():
    _app = Flask(
            import_name=__name__,
            template_folder='admin/templates/',
            static_folder='admin/static/')

    # used for encrypting cookies for handling sessions
    _app.config['SECRET_KEY'] = 'abc492ee-9739-11e6-a174-07f6b92d4a4b'
    _app.config['ROOT_URL'] = environ.env.config.get(ConfigKeys.ROOT_URL, domain=ConfigKeys.WEB, default='/')

    message_queue_type = environ.env.config.get(ConfigKeys.TYPE, domain=ConfigKeys.QUEUE, default=None)
    if message_queue_type is None and not (len(environ.env.config) == 0 or environ.env.config.get(ConfigKeys.TESTING)):
        raise RuntimeError('no message queue type specified')

    message_queue = 'redis://%s' % environ.env.config.get(ConfigKeys.HOST, domain=ConfigKeys.CACHE_SERVICE, default='')
    message_channel = 'dino_%s' % environ.env.config.get(ConfigKeys.ENVIRONMENT, default='test')

    logger.info('message_queue: %s' % message_queue)

    _socketio = SocketIO(
            _app,
            logger=logger,
            engineio_logger=os.environ.get('DINO_DEBUG', '0') == '1',
            async_mode='eventlet',
            message_queue=message_queue,
            channel=message_channel)

    # preferably "emit" should be set during env creation, but the socketio object is not created until after env is
    environ.env.out_of_scope_emit = _socketio.emit

    _app.wsgi_app = ReverseProxied(ProxyFix(_app.wsgi_app))

    return _app, _socketio 
Example #12
Source File: will.py    From W.I.L.L with MIT License 4 votes vote down vote up
def __init__(self):

        self.now = datetime.datetime.now()

        conf_file = "will.conf"
        if os.path.isfile("debug_will.conf"):
            conf_file = "debug_will.conf"
        self.conf_file = conf_file
        if os.path.isfile(conf_file):
            data_string = open(conf_file).read()
            json_data = json.loads(data_string)
            self.configuration_data = json_data
            API.configuration_data = self.configuration_data
            web.configuration_data = self.configuration_data
        else:
            print("Couldn't find will.conf file, exiting")
            os._exit(1)
        self.db = None
        app = Flask(__name__)
        app.register_blueprint(web.web)
        app.register_blueprint(API.api, url_prefix="/api")
        self.app = app
        app.logger.setLevel(logging.DEBUG)
        app.logger.addHandler(logging.StreamHandler(sys.stdout))
        app.secret_key = self.configuration_data["secret_key"]
        logfile = self.configuration_data["logfile"]
        logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                            filemode='w', filename=logfile)
        ch = logging.StreamHandler(sys.stdout)
        if self.configuration_data["debug"]:
            ch.setLevel(logging.DEBUG)
        else:
            ch.setLevel(logging.INFO)
        handler = RotatingFileHandler(logfile, maxBytes=10000000, backupCount=5)
        handler.setLevel(logging.DEBUG)
        self.app.logger.addHandler(handler)
        global log
        log = self.app.logger
        self.socketio = SocketIO(app)

        web.socketio = self.socketio

        self.socketio.on(web.disconnect_session, 'disconnect')
        self.socketio.on(web.get_updates, "get_updates")

        signal.signal(signal.SIGTERM, self.dump_events)

        self.start()

        self.socketio.run(
            app, host=self.configuration_data["host"], port=self.configuration_data["port"], debug=self.configuration_data["debug"]
            , use_reloader=False) 
Example #13
Source File: socketio_factory.py    From hydrus with MIT License 4 votes vote down vote up
def create_socket(app: Flask, session: scoped_session) -> SocketIO:
    socketio.init_app(app, logger=True)
    socketio.on_namespace(SyncNamespace(namespace='/sync', db_session=session))
    return socketio 
Example #14
Source File: server.py    From watson-online-store with Apache License 2.0 4 votes vote down vote up
def index():
    """Render our WOS web UI using a template.

    The web UI interacts with Python via Flask SocketIO.
    And uses HTML/CSS/Javascript for formatting.
    """
    return render_template('index.html', async_mode=async_mode) 
Example #15
Source File: fl_server.py    From FATE with Apache License 2.0 4 votes vote down vote up
def __init__(self, task_config_filename, host, port):
        self.task_config = load_json(task_config_filename)
        self.ready_client_sids = set()

        self.app = Flask(__name__)
        self.socketio = SocketIO(self.app, ping_timeout=3600000,
                                 ping_interval=3600000,
                                 max_http_buffer_size=int(1e32))
        self.host = host
        self.port = port
        self.client_resource = {}

        self.MIN_NUM_WORKERS = self.task_config["MIN_NUM_WORKERS"]
        self.MAX_NUM_ROUNDS = self.task_config["MAX_NUM_ROUNDS"]
        self.NUM_TOLERATE = self.task_config["NUM_TOLERATE"]
        self.NUM_CLIENTS_CONTACTED_PER_ROUND = self.task_config["NUM_CLIENTS_CONTACTED_PER_ROUND"]
        self.ROUNDS_BETWEEN_VALIDATIONS = self.task_config["ROUNDS_BETWEEN_VALIDATIONS"]

        self.logger = logging.getLogger("aggregation")
        log_dir = os.path.join('experiments', 'logs', datestr, self.task_config['log_dir'])
        os.makedirs(log_dir, exist_ok=True)
        fh = logging.FileHandler(os.path.join(log_dir, '{}.log'.format(timestr)))
        fh.setLevel(logging.INFO)
        # create console handler with a higher log level
        ch = logging.StreamHandler()
        ch.setLevel(logging.ERROR)
        # create formatter and add it to the handlers
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        fh.setFormatter(formatter)
        ch.setFormatter(formatter)
        # add the handlers to the logger
        self.logger.addHandler(fh)
        self.logger.addHandler(ch)

        self.STOP = False

        self.wait_time = 0
        self.logger.info(self.task_config)
        self.model_id = str(uuid.uuid4())

        self.aggregator = Aggregator(self.task_config, self.logger)

        #####
        # training states
        self.current_round = -1  # -1 for not yet started
        self.current_round_client_updates = []
        self.eval_client_updates = []
        #####

        # socket io messages
        self.register_handles()
        self.invalid_tolerate = 0

        @self.app.route('/')
        def dashboard():
            return render_template('dashboard.html')

        @self.app.route('/stats')
        def status_page():
            return json.dumps(self.aggregator.get_stats()) 
Example #16
Source File: restful.py    From dino with Apache License 2.0 4 votes vote down vote up
def create_app():
    _app = Flask(__name__)

    # used for encrypting cookies for handling sessions
    _app.config['SECRET_KEY'] = 'abc492ee-9739-11e6-a174-07f6b92d4a4b'

    message_queue_type = environ.env.config.get(ConfigKeys.TYPE, domain=ConfigKeys.COORDINATOR, default=None)
    if message_queue_type is None and not (len(environ.env.config) == 0 or environ.env.config.get(ConfigKeys.TESTING)):
        raise RuntimeError('no message queue type specified')

    queue_host = environ.env.config.get(ConfigKeys.HOST, domain=ConfigKeys.COORDINATOR, default='')
    message_channel = ''
    message_queue = None

    if message_queue_type == 'redis':
        message_db = environ.env.config.get(ConfigKeys.DB, domain=ConfigKeys.COORDINATOR, default=0)
        message_env = environ.env.config.get(ConfigKeys.ENVIRONMENT, default='test')
        message_channel = 'dino_{}_{}'.format(message_env, message_db)
        message_queue = 'redis://{}'.format(queue_host)

    elif message_queue_type == 'amqp':
        message_channel = 'dino_%s' % environ.env.config.get(ConfigKeys.ENVIRONMENT, default='test')
        message_queue = ';'.join(['amqp://%s:%s@%s:%s%s' % (
            environ.env.config.get(ConfigKeys.USER, domain=ConfigKeys.COORDINATOR, default=''),
            environ.env.config.get(ConfigKeys.PASSWORD, domain=ConfigKeys.COORDINATOR, default=''),
            host,
            environ.env.config.get(ConfigKeys.PORT, domain=ConfigKeys.COORDINATOR, default=''),
            environ.env.config.get(ConfigKeys.VHOST, domain=ConfigKeys.COORDINATOR, default=''),
        ) for host in queue_host.split(';')])

    logger.info('message_queue: %s' % message_queue)

    _api = Api(_app)

    _socketio = SocketIO(
            _app,
            logger=logger,
            engineio_logger=os.environ.get('DINO_DEBUG', '0') == '1',
            async_mode='eventlet',
            message_queue=message_queue,
            channel=message_channel)

    # preferably "emit" should be set during env creation, but the socketio object is not created until after env is
    environ.env.out_of_scope_emit = _socketio.emit

    _app.wsgi_app = ProxyFix(_app.wsgi_app)
    return _app, _api, _socketio 
Example #17
Source File: server.py    From dino with Apache License 2.0 4 votes vote down vote up
def create_app():
    _app = Flask(__name__)

    # used for encrypting cookies for handling sessions
    _app.config['SECRET_KEY'] = 'abc492ee-9739-11e6-a174-07f6b92d4a4b'

    message_queue_type = environ.env.config.get(ConfigKeys.TYPE, domain=ConfigKeys.COORDINATOR, default=None)
    if message_queue_type is None and not (len(environ.env.config) == 0 or environ.env.config.get(ConfigKeys.TESTING)):
        raise RuntimeError('no message queue type specified')

    queue_host = environ.env.config.get(ConfigKeys.HOST, domain=ConfigKeys.COORDINATOR, default='')
    message_channel = ''
    message_queue = None

    if message_queue_type == 'redis':
        message_db = environ.env.config.get(ConfigKeys.DB, domain=ConfigKeys.COORDINATOR, default=0)
        message_env = environ.env.config.get(ConfigKeys.ENVIRONMENT, default='test')
        message_channel = 'dino_{}_{}'.format(message_env, message_db)
        message_queue = 'redis://{}'.format(queue_host)

    elif message_queue_type == 'amqp':
        message_channel = 'dino_%s' % environ.env.config.get(ConfigKeys.ENVIRONMENT, default='test')
        message_queue = ';'.join(['amqp://%s:%s@%s:%s%s' % (
            environ.env.config.get(ConfigKeys.USER, domain=ConfigKeys.COORDINATOR, default=''),
            environ.env.config.get(ConfigKeys.PASSWORD, domain=ConfigKeys.COORDINATOR, default=''),
            host,
            environ.env.config.get(ConfigKeys.PORT, domain=ConfigKeys.COORDINATOR, default=''),
            environ.env.config.get(ConfigKeys.VHOST, domain=ConfigKeys.COORDINATOR, default=''),
        ) for host in queue_host.split(';')])

    elif not environ.env.config.get(ConfigKeys.TESTING, False):
        raise RuntimeError('unknown message queue type {} specified: {}'.format(message_queue_type, environ.env.config.params))

    logger.info('message_queue: %s' % message_queue)
    cors = environ.env.config.get(ConfigKeys.CORS_ORIGINS, default='*').split(',')
    if cors == ['*']:
        cors = cors[0]

    _socketio = SocketIO(
        _app,
        logger=socket_logger,
        engineio_logger=os.environ.get('DINO_DEBUG', '0') == '1',
        async_mode='eventlet',
        message_queue=message_queue,
        channel=message_channel,
        cors_allowed_origins=cors
    )

    # preferably "emit" should be set during env creation, but the socketio object is not created until after env is
    environ.env.out_of_scope_emit = _socketio.emit

    _app.wsgi_app = ProxyFix(_app.wsgi_app)
    return _app, _socketio 
Example #18
Source File: app.py    From hyperface with MIT License 4 votes vote down vote up
def new_server(viewer_queue, stop_page, port, secret_key):
    # create server
    app = Flask(__name__, static_url_path='/static')
    app.config['SECRET_KEY'] = secret_key
    # must be 'threading' for broadcast emitting
    socketio = SocketIO(app, async_mode='threading',
                        logger=False, engineio_logger=False)

    # rooting
    @app.route('/')
    def __index():
        logger.info('Render viewer page')
        return render_template('index.html', script="index.js")

    if stop_page:
        @app.route('/stop')
        def __stop():
            socketio.stop()
            logger.info('Server stop request')
            return 'This server is stopped'

    @socketio.on('connect', namespace=IO_NAMESPACE)
    def __on_viewer_connect():
        logger.info('New viewer connection is established')

    @socketio.on('disconnect', namespace=IO_NAMESPACE)
    def __on_viewer_disconnect():
        logger.info('Viewer connection is closed')

    @socketio.on('update', namespace=IO_NAMESPACE)
    def __on_update():
        logger.info('Image updating request is received')
        # get all of current data
        emit_data = buffering_thread.get_data_all()
        # emit all
        logger.debug('Emit for update all')
        emit('update', emit_data, namespace=IO_NAMESPACE)

    def update_event(tab, name, data):
        emit_data = [[tab, name, data]]  # single data
        # broadcast emit
        logger.debug('Broadcast emit for update (tab: %s, name: %s)' %
                     (str(tab), str(name)))
        socketio.emit('update', emit_data, namespace=IO_NAMESPACE)

    # create image updating thread
    if viewer_queue:
        logger.info('Start image buffering thread')
        buffering_thread = ImageBufferingThread(viewer_queue)
        buffering_thread.daemon = True
        buffering_thread.start()
        buffering_thread.register_update_event_func(update_event)

    # start server
    logger.info('Start server on port %d' % port)
    socketio.run(app, host='0.0.0.0', port=port, debug=False, log_output=False)
    logger.info('Stop server on port %d' % port)