本文整理汇总了Python中flask_socketio.SocketIO方法的典型用法代码示例。如果您正苦于以下问题:Python flask_socketio.SocketIO方法的具体用法?Python flask_socketio.SocketIO怎么用?Python flask_socketio.SocketIO使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类flask_socketio
的用法示例。
在下文中一共展示了flask_socketio.SocketIO方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_app
# 需要导入模块: import flask_socketio [as 别名]
# 或者: from flask_socketio import SocketIO [as 别名]
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)
示例2: init
# 需要导入模块: import flask_socketio [as 别名]
# 或者: from flask_socketio import SocketIO [as 别名]
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
示例3: main
# 需要导入模块: import flask_socketio [as 别名]
# 或者: from flask_socketio import SocketIO [as 别名]
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")
示例4: create_app
# 需要导入模块: import flask_socketio [as 别名]
# 或者: from flask_socketio import SocketIO [as 别名]
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
示例5: run_socket_server
# 需要导入模块: import flask_socketio [as 别名]
# 或者: from flask_socketio import SocketIO [as 别名]
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
)
示例6: create_socket
# 需要导入模块: import flask_socketio [as 别名]
# 或者: from flask_socketio import SocketIO [as 别名]
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
示例7: create_app
# 需要导入模块: import flask_socketio [as 别名]
# 或者: from flask_socketio import SocketIO [as 别名]
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
示例8: init_socket_io
# 需要导入模块: import flask_socketio [as 别名]
# 或者: from flask_socketio import SocketIO [as 别名]
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
示例9: index
# 需要导入模块: import flask_socketio [as 别名]
# 或者: from flask_socketio import SocketIO [as 别名]
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)
示例10: send_message
# 需要导入模块: import flask_socketio [as 别名]
# 或者: from flask_socketio import SocketIO [as 别名]
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})
示例11: do_connect
# 需要导入模块: import flask_socketio [as 别名]
# 或者: from flask_socketio import SocketIO [as 别名]
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
示例12: __init__
# 需要导入模块: import flask_socketio [as 别名]
# 或者: from flask_socketio import SocketIO [as 别名]
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)
示例13: create_app
# 需要导入模块: import flask_socketio [as 别名]
# 或者: from flask_socketio import SocketIO [as 别名]
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
示例14: create_app
# 需要导入模块: import flask_socketio [as 别名]
# 或者: from flask_socketio import SocketIO [as 别名]
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
示例15: create_app
# 需要导入模块: import flask_socketio [as 别名]
# 或者: from flask_socketio import SocketIO [as 别名]
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