codekingpro/portable-devtools
114k
1from functools import wraps2import os3import sys4 5# make sure gevent-socketio is not installed, as it conflicts with6# python-socketio7gevent_socketio_found = True8try:9 from socketio import socketio_manage # noqa: F40110except ImportError:11 gevent_socketio_found = False12if gevent_socketio_found:13 print('The gevent-socketio package is incompatible with this version of '14 'the Flask-SocketIO extension. Please uninstall it, and then '15 'install the latest version of python-socketio in its place.')16 sys.exit(1)17 18import flask19from flask import has_request_context, json as flask_json20from flask.sessions import SessionMixin21import socketio22from socketio.exceptions import ConnectionRefusedError # noqa: F40123from werkzeug.debug import DebuggedApplication24from werkzeug._reloader import run_with_reloader25 26from .namespace import Namespace27from .test_client import SocketIOTestClient28 29 30class _SocketIOMiddleware(socketio.WSGIApp):31 """This WSGI middleware simply exposes the Flask application in the WSGI32 environment before executing the request.33 """34 def __init__(self, socketio_app, flask_app, socketio_path='socket.io'):35 self.flask_app = flask_app36 super(_SocketIOMiddleware, self).__init__(socketio_app,37 flask_app.wsgi_app,38 socketio_path=socketio_path)39 40 def __call__(self, environ, start_response):41 environ = environ.copy()42 environ['flask.app'] = self.flask_app43 return super(_SocketIOMiddleware, self).__call__(environ,44 start_response)45 46 47class _ManagedSession(dict, SessionMixin):48 """This class is used for user sessions that are managed by49 Flask-SocketIO. It is simple dict, expanded with the Flask session50 attributes."""51 pass52 53 54class SocketIO(object):55 """Create a Flask-SocketIO server.56 57 :param app: The flask application instance. If the application instance58 isn't known at the time this class is instantiated, then call59 ``socketio.init_app(app)`` once the application instance is60 available.61 :param manage_session: If set to ``True``, this extension manages the user62 session for Socket.IO events. If set to ``False``,63 Flask's own session management is used. When using64 Flask's cookie based sessions it is recommended that65 you leave this set to the default of ``True``. When66 using server-side sessions, a ``False`` setting67 enables sharing the user session between HTTP routes68 and Socket.IO events.69 :param message_queue: A connection URL for a message queue service the70 server can use for multi-process communication. A71 message queue is not required when using a single72 server process.73 :param channel: The channel name, when using a message queue. If a channel74 isn't specified, a default channel will be used. If75 multiple clusters of SocketIO processes need to use the76 same message queue without interfering with each other,77 then each cluster should use a different channel.78 :param path: The path where the Socket.IO server is exposed. Defaults to79 ``'socket.io'``. Leave this as is unless you know what you are80 doing.81 :param resource: Alias to ``path``.82 :param kwargs: Socket.IO and Engine.IO server options.83 84 The Socket.IO server options are detailed below:85 86 :param client_manager: The client manager instance that will manage the87 client list. When this is omitted, the client list88 is stored in an in-memory structure, so the use of89 multiple connected servers is not possible. In most90 cases, this argument does not need to be set91 explicitly.92 :param logger: To enable logging set to ``True`` or pass a logger object to93 use. To disable logging set to ``False``. The default is94 ``False``. Note that fatal errors will be logged even when95 ``logger`` is ``False``.96 :param json: An alternative json module to use for encoding and decoding97 packets. Custom json modules must have ``dumps`` and ``loads``98 functions that are compatible with the standard library99 versions. To use the same json encoder and decoder as a Flask100 application, use ``flask.json``.101 :param async_handlers: If set to ``True``, event handlers for a client are102 executed in separate threads. To run handlers for a103 client synchronously, set to ``False``. The default104 is ``True``.105 :param always_connect: When set to ``False``, new connections are106 provisory until the connect handler returns107 something other than ``False``, at which point they108 are accepted. When set to ``True``, connections are109 immediately accepted, and then if the connect110 handler returns ``False`` a disconnect is issued.111 Set to ``True`` if you need to emit events from the112 connect handler and your client is confused when it113 receives events before the connection acceptance.114 In any other case use the default of ``False``.115 116 The Engine.IO server configuration supports the following settings:117 118 :param async_mode: The asynchronous model to use. See the Deployment119 section in the documentation for a description of the120 available options. Valid async modes are ``threading``,121 ``eventlet``, ``gevent`` and ``gevent_uwsgi``. If this122 argument is not given, ``eventlet`` is tried first, then123 ``gevent_uwsgi``, then ``gevent``, and finally124 ``threading``. The first async mode that has all its125 dependencies installed is then one that is chosen.126 :param ping_interval: The interval in seconds at which the server pings127 the client. The default is 25 seconds. For advanced128 control, a two element tuple can be given, where129 the first number is the ping interval and the second130 is a grace period added by the server.131 :param ping_timeout: The time in seconds that the client waits for the132 server to respond before disconnecting. The default133 is 5 seconds.134 :param max_http_buffer_size: The maximum size of a message when using the135 polling transport. The default is 1,000,000136 bytes.137 :param allow_upgrades: Whether to allow transport upgrades or not. The138 default is ``True``.139 :param http_compression: Whether to compress packages when using the140 polling transport. The default is ``True``.141 :param compression_threshold: Only compress messages when their byte size142 is greater than this value. The default is143 1024 bytes.144 :param cookie: If set to a string, it is the name of the HTTP cookie the145 server sends back to the client containing the client146 session id. If set to a dictionary, the ``'name'`` key147 contains the cookie name and other keys define cookie148 attributes, where the value of each attribute can be a149 string, a callable with no arguments, or a boolean. If set150 to ``None`` (the default), a cookie is not sent to the151 client.152 :param cors_allowed_origins: Origin or list of origins that are allowed to153 connect to this server. Only the same origin154 is allowed by default. Set this argument to155 ``'*'`` to allow all origins, or to ``[]`` to156 disable CORS handling.157 :param cors_credentials: Whether credentials (cookies, authentication) are158 allowed in requests to this server. The default is159 ``True``.160 :param monitor_clients: If set to ``True``, a background task will ensure161 inactive clients are closed. Set to ``False`` to162 disable the monitoring task (not recommended). The163 default is ``True``.164 :param engineio_logger: To enable Engine.IO logging set to ``True`` or pass165 a logger object to use. To disable logging set to166 ``False``. The default is ``False``. Note that167 fatal errors are logged even when168 ``engineio_logger`` is ``False``.169 """170 171 def __init__(self, app=None, **kwargs):172 self.server = None173 self.server_options = {}174 self.wsgi_server = None175 self.handlers = []176 self.namespace_handlers = []177 self.exception_handlers = {}178 self.default_exception_handler = None179 self.manage_session = True180 # We can call init_app when:181 # - we were given the Flask app instance (standard initialization)182 # - we were not given the app, but we were given a message_queue183 # (standard initialization for auxiliary process)184 # In all other cases we collect the arguments and assume the client185 # will call init_app from an app factory function.186 if app is not None or 'message_queue' in kwargs:187 self.init_app(app, **kwargs)188 else:189 self.server_options.update(kwargs)190 191 def init_app(self, app, **kwargs):192 if app is not None:193 if not hasattr(app, 'extensions'):194 app.extensions = {} # pragma: no cover195 app.extensions['socketio'] = self196 self.server_options.update(kwargs)197 self.manage_session = self.server_options.pop('manage_session',198 self.manage_session)199 200 if 'client_manager' not in kwargs:201 url = self.server_options.get('message_queue', None)202 channel = self.server_options.pop('channel', 'flask-socketio')203 write_only = app is None204 if url:205 if url.startswith(('redis://', "rediss://")):206 queue_class = socketio.RedisManager207 elif url.startswith(('kafka://')):208 queue_class = socketio.KafkaManager209 elif url.startswith('zmq'):210 queue_class = socketio.ZmqManager211 else:212 queue_class = socketio.KombuManager213 queue = queue_class(url, channel=channel,214 write_only=write_only)215 self.server_options['client_manager'] = queue216 217 if 'json' in self.server_options and \218 self.server_options['json'] == flask_json:219 # flask's json module is tricky to use because its output220 # changes when it is invoked inside or outside the app context221 # so here to prevent any ambiguities we replace it with wrappers222 # that ensure that the app context is always present223 class FlaskSafeJSON(object):224 @staticmethod225 def dumps(*args, **kwargs):226 with app.app_context():227 return flask_json.dumps(*args, **kwargs)228 229 @staticmethod230 def loads(*args, **kwargs):231 with app.app_context():232 return flask_json.loads(*args, **kwargs)233 234 self.server_options['json'] = FlaskSafeJSON235 236 resource = self.server_options.pop('path', None) or \237 self.server_options.pop('resource', None) or 'socket.io'238 if resource.startswith('/'):239 resource = resource[1:]240 if os.environ.get('FLASK_RUN_FROM_CLI'):241 if self.server_options.get('async_mode') is None:242 self.server_options['async_mode'] = 'threading'243 self.server = socketio.Server(**self.server_options)244 self.async_mode = self.server.async_mode245 for handler in self.handlers:246 self.server.on(handler[0], handler[1], namespace=handler[2])247 for namespace_handler in self.namespace_handlers:248 self.server.register_namespace(namespace_handler)249 250 if app is not None:251 # here we attach the SocketIO middleware to the SocketIO object so252 # it can be referenced later if debug middleware needs to be253 # inserted254 self.sockio_mw = _SocketIOMiddleware(self.server, app,255 socketio_path=resource)256 app.wsgi_app = self.sockio_mw257 258 def on(self, message, namespace=None):259 """Decorator to register a SocketIO event handler.260 261 This decorator must be applied to SocketIO event handlers. Example::262 263 @socketio.on('my event', namespace='/chat')264 def handle_my_custom_event(json):265 print('received json: ' + str(json))266 267 :param message: The name of the event. This is normally a user defined268 string, but a few event names are already defined. Use269 ``'message'`` to define a handler that takes a string270 payload, ``'json'`` to define a handler that takes a271 JSON blob payload, ``'connect'`` or ``'disconnect'``272 to create handlers for connection and disconnection273 events.274 :param namespace: The namespace on which the handler is to be275 registered. Defaults to the global namespace.276 """277 namespace = namespace or '/'278 279 def decorator(handler):280 @wraps(handler)281 def _handler(sid, *args):282 return self._handle_event(handler, message, namespace, sid,283 *args)284 285 if self.server:286 self.server.on(message, _handler, namespace=namespace)287 else:288 self.handlers.append((message, _handler, namespace))289 return handler290 return decorator291 292 def on_error(self, namespace=None):293 """Decorator to define a custom error handler for SocketIO events.294 295 This decorator can be applied to a function that acts as an error296 handler for a namespace. This handler will be invoked when a SocketIO297 event handler raises an exception. The handler function must accept one298 argument, which is the exception raised. Example::299 300 @socketio.on_error(namespace='/chat')301 def chat_error_handler(e):302 print('An error has occurred: ' + str(e))303 304 :param namespace: The namespace for which to register the error305 handler. Defaults to the global namespace.306 """307 namespace = namespace or '/'308 309 def decorator(exception_handler):310 if not callable(exception_handler):311 raise ValueError('exception_handler must be callable')312 self.exception_handlers[namespace] = exception_handler313 return exception_handler314 return decorator315 316 def on_error_default(self, exception_handler):317 """Decorator to define a default error handler for SocketIO events.318 319 This decorator can be applied to a function that acts as a default320 error handler for any namespaces that do not have a specific handler.321 Example::322 323 @socketio.on_error_default324 def error_handler(e):325 print('An error has occurred: ' + str(e))326 """327 if not callable(exception_handler):328 raise ValueError('exception_handler must be callable')329 self.default_exception_handler = exception_handler330 return exception_handler331 332 def on_event(self, message, handler, namespace=None):333 """Register a SocketIO event handler.334 335 ``on_event`` is the non-decorator version of ``'on'``.336 337 Example::338 339 def on_foo_event(json):340 print('received json: ' + str(json))341 342 socketio.on_event('my event', on_foo_event, namespace='/chat')343 344 :param message: The name of the event. This is normally a user defined345 string, but a few event names are already defined. Use346 ``'message'`` to define a handler that takes a string347 payload, ``'json'`` to define a handler that takes a348 JSON blob payload, ``'connect'`` or ``'disconnect'``349 to create handlers for connection and disconnection350 events.351 :param handler: The function that handles the event.352 :param namespace: The namespace on which the handler is to be353 registered. Defaults to the global namespace.354 """355 self.on(message, namespace=namespace)(handler)356 357 def event(self, *args, **kwargs):358 """Decorator to register an event handler.359 360 This is a simplified version of the ``on()`` method that takes the361 event name from the decorated function.362 363 Example usage::364 365 @socketio.event366 def my_event(data):367 print('Received data: ', data)368 369 The above example is equivalent to::370 371 @socketio.on('my_event')372 def my_event(data):373 print('Received data: ', data)374 375 A custom namespace can be given as an argument to the decorator::376 377 @socketio.event(namespace='/test')378 def my_event(data):379 print('Received data: ', data)380 """381 if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):382 # the decorator was invoked without arguments383 # args[0] is the decorated function384 return self.on(args[0].__name__)(args[0])385 else:386 # the decorator was invoked with arguments387 def set_handler(handler):388 return self.on(handler.__name__, *args, **kwargs)(handler)389 390 return set_handler391 392 def on_namespace(self, namespace_handler):393 if not isinstance(namespace_handler, Namespace):394 raise ValueError('Not a namespace instance.')395 namespace_handler._set_socketio(self)396 if self.server:397 self.server.register_namespace(namespace_handler)398 else:399 self.namespace_handlers.append(namespace_handler)400 401 def emit(self, event, *args, **kwargs):402 """Emit a server generated SocketIO event.403 404 This function emits a SocketIO event to one or more connected clients.405 A JSON blob can be attached to the event as payload. This function can406 be used outside of a SocketIO event context, so it is appropriate to407 use when the server is the originator of an event, outside of any408 client context, such as in a regular HTTP request handler or a409 background task. Example::410 411 @app.route('/ping')412 def ping():413 socketio.emit('ping event', {'data': 42}, namespace='/chat')414 415 :param event: The name of the user event to emit.416 :param args: A dictionary with the JSON data to send as payload.417 :param namespace: The namespace under which the message is to be sent.418 Defaults to the global namespace.419 :param to: Send the message to all the users in the given room, or to420 the user with the given session ID. If this parameter is not421 included, the event is sent to all connected users.422 :param include_self: ``True`` to include the sender when broadcasting423 or addressing a room, or ``False`` to send to424 everyone but the sender.425 :param skip_sid: The session id of a client to ignore when broadcasting426 or addressing a room. This is typically set to the427 originator of the message, so that everyone except428 that client receive the message. To skip multiple sids429 pass a list.430 :param callback: If given, this function will be called to acknowledge431 that the client has received the message. The432 arguments that will be passed to the function are433 those provided by the client. Callback functions can434 only be used when addressing an individual client.435 """436 namespace = kwargs.pop('namespace', '/')437 to = kwargs.pop('to', None) or kwargs.pop('room', None)438 include_self = kwargs.pop('include_self', True)439 skip_sid = kwargs.pop('skip_sid', None)440 if not include_self and not skip_sid:441 skip_sid = flask.request.sid442 callback = kwargs.pop('callback', None)443 if callback:444 # wrap the callback so that it sets app app and request contexts445 sid = None446 original_callback = callback447 original_namespace = namespace448 if has_request_context():449 sid = getattr(flask.request, 'sid', None)450 original_namespace = getattr(flask.request, 'namespace', None)451 452 def _callback_wrapper(*args):453 return self._handle_event(original_callback, None,454 original_namespace, sid, *args)455 456 if sid:457 # the callback wrapper above will install a request context458 # before invoking the original callback459 # we only use it if the emit was issued from a Socket.IO460 # populated request context (i.e. request.sid is defined)461 callback = _callback_wrapper462 self.server.emit(event, *args, namespace=namespace, to=to,463 skip_sid=skip_sid, callback=callback, **kwargs)464 465 def call(self, event, *args, **kwargs): # pragma: no cover466 """Emit a SocketIO event and wait for the response.467 468 This method issues an emit with a callback and waits for the callback469 to be invoked by the client before returning. If the callback isn’t470 invoked before the timeout, then a TimeoutError exception is raised. If471 the Socket.IO connection drops during the wait, this method still waits472 until the specified timeout. Example::473 474 def get_status(client, data):475 status = call('status', {'data': data}, to=client)476 477 :param event: The name of the user event to emit.478 :param args: A dictionary with the JSON data to send as payload.479 :param namespace: The namespace under which the message is to be sent.480 Defaults to the global namespace.481 :param to: The session ID of the recipient client.482 :param timeout: The waiting timeout. If the timeout is reached before483 the client acknowledges the event, then a484 ``TimeoutError`` exception is raised. The default is 60485 seconds.486 :param ignore_queue: Only used when a message queue is configured. If487 set to ``True``, the event is emitted to the488 client directly, without going through the queue.489 This is more efficient, but only works when a490 single server process is used, or when there is a491 single addressee. It is recommended to always492 leave this parameter with its default value of493 ``False``.494 """495 namespace = kwargs.pop('namespace', '/')496 to = kwargs.pop('to', None) or kwargs.pop('room', None)497 return self.server.call(event, *args, namespace=namespace, to=to,498 **kwargs)499 500 def send(self, data, json=False, namespace=None, to=None,501 callback=None, include_self=True, skip_sid=None, **kwargs):502 """Send a server-generated SocketIO message.503 504 This function sends a simple SocketIO message to one or more connected505 clients. The message can be a string or a JSON blob. This is a simpler506 version of ``emit()``, which should be preferred. This function can be507 used outside of a SocketIO event context, so it is appropriate to use508 when the server is the originator of an event.509 510 :param data: The message to send, either a string or a JSON blob.511 :param json: ``True`` if ``message`` is a JSON blob, ``False``512 otherwise.513 :param namespace: The namespace under which the message is to be sent.514 Defaults to the global namespace.515 :param to: Send the message to all the users in the given room, or to516 the user with the given session ID. If this parameter is not517 included, the event is sent to all connected users.518 :param include_self: ``True`` to include the sender when broadcasting519 or addressing a room, or ``False`` to send to520 everyone but the sender.521 :param skip_sid: The session id of a client to ignore when broadcasting522 or addressing a room. This is typically set to the523 originator of the message, so that everyone except524 that client receive the message. To skip multiple sids525 pass a list.526 :param callback: If given, this function will be called to acknowledge527 that the client has received the message. The528 arguments that will be passed to the function are529 those provided by the client. Callback functions can530 only be used when addressing an individual client.531 """532 skip_sid = flask.request.sid if not include_self else skip_sid533 if json:534 self.emit('json', data, namespace=namespace, to=to,535 skip_sid=skip_sid, callback=callback, **kwargs)536 else:537 self.emit('message', data, namespace=namespace, to=to,538 skip_sid=skip_sid, callback=callback, **kwargs)539 540 def close_room(self, room, namespace=None):541 """Close a room.542 543 This function removes any users that are in the given room and then544 deletes the room from the server. This function can be used outside545 of a SocketIO event context.546 547 :param room: The name of the room to close.548 :param namespace: The namespace under which the room exists. Defaults549 to the global namespace.550 """551 self.server.close_room(room, namespace)552 553 def run(self, app, host=None, port=None, **kwargs): # pragma: no cover554 """Run the SocketIO web server.555 556 :param app: The Flask application instance.557 :param host: The hostname or IP address for the server to listen on.558 Defaults to 127.0.0.1.559 :param port: The port number for the server to listen on. Defaults to560 5000.561 :param debug: ``True`` to start the server in debug mode, ``False`` to562 start in normal mode.563 :param use_reloader: ``True`` to enable the Flask reloader, ``False``564 to disable it.565 :param reloader_options: A dictionary with options that are passed to566 the Flask reloader, such as ``extra_files``,567 ``reloader_type``, etc.568 :param extra_files: A list of additional files that the Flask569 reloader should watch. Defaults to ``None``.570 Deprecated, use ``reloader_options`` instead.571 :param log_output: If ``True``, the server logs all incoming572 connections. If ``False`` logging is disabled.573 Defaults to ``True`` in debug mode, ``False``574 in normal mode. Unused when the threading async575 mode is used.576 :param allow_unsafe_werkzeug: Set to ``True`` to allow the use of the577 Werkzeug web server in a production578 setting. Default is ``False``. Set to579 ``True`` at your own risk.580 :param kwargs: Additional web server options. The web server options581 are specific to the server used in each of the supported582 async modes. Note that options provided here will583 not be seen when using an external web server such584 as gunicorn, since this method is not called in that585 case.586 """587 if host is None:588 host = '127.0.0.1'589 if port is None:590 server_name = app.config['SERVER_NAME']591 if server_name and ':' in server_name:592 port = int(server_name.rsplit(':', 1)[1])593 else:594 port = 5000595 596 debug = kwargs.pop('debug', app.debug)597 log_output = kwargs.pop('log_output', debug)598 use_reloader = kwargs.pop('use_reloader', debug)599 extra_files = kwargs.pop('extra_files', None)600 reloader_options = kwargs.pop('reloader_options', {})601 if extra_files:602 reloader_options['extra_files'] = extra_files603 604 app.debug = debug605 if app.debug and self.server.eio.async_mode != 'threading':606 # put the debug middleware between the SocketIO middleware607 # and the Flask application instance608 #609 # mw1 mw2 mw3 Flask app610 # o ---- o ---- o ---- o611 # /612 # o Flask-SocketIO613 # \ middleware614 # o615 # Flask-SocketIO WebSocket handler616 #617 # BECOMES618 #619 # dbg-mw mw1 mw2 mw3 Flask app620 # o ---- o ---- o ---- o ---- o621 # /622 # o Flask-SocketIO623 # \ middleware624 # o625 # Flask-SocketIO WebSocket handler626 #627 self.sockio_mw.wsgi_app = DebuggedApplication(628 self.sockio_mw.wsgi_app, evalex=True)629 630 allow_unsafe_werkzeug = kwargs.pop('allow_unsafe_werkzeug', False)631 if self.server.eio.async_mode == 'threading':632 try:633 import simple_websocket # noqa: F401634 except ImportError:635 from werkzeug._internal import _log636 _log('warning', 'WebSocket transport not available. Install '637 'simple-websocket for improved performance.')638 if not sys.stdin or not sys.stdin.isatty(): # pragma: no cover639 if not allow_unsafe_werkzeug:640 raise RuntimeError('The Werkzeug web server is not '641 'designed to run in production. Pass '642 'allow_unsafe_werkzeug=True to the '643 'run() method to disable this error.')644 else:645 from werkzeug._internal import _log646 _log('warning', ('Werkzeug appears to be used in a '647 'production deployment. Consider '648 'switching to a production web server '649 'instead.'))650 app.run(host=host, port=port, threaded=True,651 use_reloader=use_reloader, **reloader_options, **kwargs)652 elif self.server.eio.async_mode == 'eventlet':653 def run_server():654 import eventlet655 import eventlet.wsgi656 import eventlet.green657 addresses = eventlet.green.socket.getaddrinfo(host, port)658 if not addresses:659 raise RuntimeError(660 'Could not resolve host to a valid address')661 eventlet_socket = eventlet.listen(addresses[0][4],662 addresses[0][0])663 664 # If provided an SSL argument, use an SSL socket665 ssl_args = ['keyfile', 'certfile', 'server_side', 'cert_reqs',666 'ssl_version', 'ca_certs',667 'do_handshake_on_connect', 'suppress_ragged_eofs',668 'ciphers']669 ssl_params = {k: kwargs[k] for k in kwargs670 if k in ssl_args and kwargs[k] is not None}671 for k in ssl_args:672 kwargs.pop(k, None)673 if len(ssl_params) > 0:674 ssl_params['server_side'] = True # Listening requires true675 eventlet_socket = eventlet.wrap_ssl(eventlet_socket,676 **ssl_params)677 678 eventlet.wsgi.server(eventlet_socket, app,679 log_output=log_output, **kwargs)680 681 if use_reloader:682 run_with_reloader(run_server, **reloader_options)683 else:684 run_server()685 elif self.server.eio.async_mode == 'gevent':686 from gevent import pywsgi687 try:688 from geventwebsocket.handler import WebSocketHandler689 websocket = True690 except ImportError:691 app.logger.warning(692 'WebSocket transport not available. Install '693 'gevent-websocket for improved performance.')694 websocket = False695 696 log = 'default'697 if not log_output:698 log = None699 if websocket:700 self.wsgi_server = pywsgi.WSGIServer(701 (host, port), app, handler_class=WebSocketHandler,702 log=log, **kwargs)703 else:704 self.wsgi_server = pywsgi.WSGIServer((host, port), app,705 log=log, **kwargs)706 707 if use_reloader:708 # monkey patching is required by the reloader709 from gevent import monkey710 monkey.patch_thread()711 monkey.patch_time()712 713 def run_server():714 self.wsgi_server.serve_forever()715 716 run_with_reloader(run_server, **reloader_options)717 else:718 self.wsgi_server.serve_forever()719 720 def stop(self):721 """Stop a running SocketIO web server.722 723 This method must be called from a HTTP or SocketIO handler function.724 """725 if self.server.eio.async_mode == 'threading':726 func = flask.request.environ.get('werkzeug.server.shutdown')727 if func:728 func()729 else:730 raise RuntimeError('Cannot stop unknown web server')731 elif self.server.eio.async_mode == 'eventlet':732 raise SystemExit733 elif self.server.eio.async_mode == 'gevent':734 self.wsgi_server.stop()735 736 def start_background_task(self, target, *args, **kwargs):737 """Start a background task using the appropriate async model.738 739 This is a utility function that applications can use to start a740 background task using the method that is compatible with the741 selected async mode.742 743 :param target: the target function to execute.744 :param args: arguments to pass to the function.745 :param kwargs: keyword arguments to pass to the function.746 747 This function returns an object that represents the background task,748 on which the ``join()`` method can be invoked to wait for the task to749 complete.750 """751 return self.server.start_background_task(target, *args, **kwargs)752 753 def sleep(self, seconds=0):754 """Sleep for the requested amount of time using the appropriate async755 model.756 757 This is a utility function that applications can use to put a task to758 sleep without having to worry about using the correct call for the759 selected async mode.760 """761 return self.server.sleep(seconds)762 763 def test_client(self, app, namespace=None, query_string=None,764 headers=None, auth=None, flask_test_client=None):765 """The Socket.IO test client is useful for testing a Flask-SocketIO766 server. It works in a similar way to the Flask Test Client, but767 adapted to the Socket.IO server.768 769 :param app: The Flask application instance.770 :param namespace: The namespace for the client. If not provided, the771 client connects to the server on the global772 namespace.773 :param query_string: A string with custom query string arguments.774 :param headers: A dictionary with custom HTTP headers.775 :param auth: Optional authentication data, given as a dictionary.776 :param flask_test_client: The instance of the Flask test client777 currently in use. Passing the Flask test778 client is optional, but is necessary if you779 want the Flask user session and any other780 cookies set in HTTP routes accessible from781 Socket.IO events.782 """783 return SocketIOTestClient(app, self, namespace=namespace,784 query_string=query_string, headers=headers,785 auth=auth,786 flask_test_client=flask_test_client)787 788 def _handle_event(self, handler, message, namespace, sid, *args):789 environ = self.server.get_environ(sid, namespace=namespace)790 if not environ:791 # we don't have record of this client, ignore this event792 return '', 400793 app = environ['flask.app']794 with app.request_context(environ):795 if self.manage_session:796 # manage a separate session for this client's Socket.IO events797 # created as a copy of the regular user session798 if 'saved_session' not in environ:799 environ['saved_session'] = _ManagedSession(flask.session)800 session_obj = environ['saved_session']801 if hasattr(flask, 'globals') and \802 hasattr(flask.globals, 'request_ctx'):803 # update session for Flask >= 2.2804 ctx = flask.globals.request_ctx._get_current_object()805 else: # pragma: no cover806 # update session for Flask < 2.2807 ctx = flask._request_ctx_stack.top808 ctx.session = session_obj809 else:810 # let Flask handle the user session811 # for cookie based sessions, this effectively freezes the812 # session to its state at connection time813 # for server-side sessions, this allows HTTP and Socket.IO to814 # share the session, with both having read/write access to it815 session_obj = flask.session._get_current_object()816 flask.request.sid = sid817 flask.request.namespace = namespace818 flask.request.event = {'message': message, 'args': args}819 try:820 if message == 'connect':821 auth = args[1] if len(args) > 1 else None822 try:823 ret = handler(auth)824 except TypeError:825 ret = handler()826 else:827 ret = handler(*args)828 except ConnectionRefusedError:829 raise # let this error bubble up to python-socketio830 except:831 err_handler = self.exception_handlers.get(832 namespace, self.default_exception_handler)833 if err_handler is None:834 raise835 type, value, traceback = sys.exc_info()836 return err_handler(value)837 if not self.manage_session:838 # when Flask is managing the user session, it needs to save it839 if not hasattr(session_obj, 'modified') or \840 session_obj.modified:841 resp = app.response_class()842 app.session_interface.save_session(app, session_obj, resp)843 return ret844 845 846def emit(event, *args, **kwargs):847 """Emit a SocketIO event.848 849 This function emits a SocketIO event to one or more connected clients. A850 JSON blob can be attached to the event as payload. This is a function that851 can only be called from a SocketIO event handler, as in obtains some852 information from the current client context. Example::853 854 @socketio.on('my event')855 def handle_my_custom_event(json):856 emit('my response', {'data': 42})857 858 :param event: The name of the user event to emit.859 :param args: A dictionary with the JSON data to send as payload.860 :param namespace: The namespace under which the message is to be sent.861 Defaults to the namespace used by the originating event.862 A ``'/'`` can be used to explicitly specify the global863 namespace.864 :param callback: Callback function to invoke with the client's865 acknowledgement.866 :param broadcast: ``True`` to send the message to all clients, or ``False``867 to only reply to the sender of the originating event.868 :param to: Send the message to all the users in the given room, or to the869 user with the given session ID. If this argument is not set and870 ``broadcast`` is ``False``, then the message is sent only to the871 originating user.872 :param include_self: ``True`` to include the sender when broadcasting or873 addressing a room, or ``False`` to send to everyone874 but the sender.875 :param skip_sid: The session id of a client to ignore when broadcasting876 or addressing a room. This is typically set to the877 originator of the message, so that everyone except878 that client receive the message. To skip multiple sids879 pass a list.880 :param ignore_queue: Only used when a message queue is configured. If881 set to ``True``, the event is emitted to the882 clients directly, without going through the queue.883 This is more efficient, but only works when a884 single server process is used, or when there is a885 single addressee. It is recommended to always leave886 this parameter with its default value of ``False``.887 """888 if 'namespace' in kwargs:889 namespace = kwargs['namespace']890 else:891 namespace = flask.request.namespace892 callback = kwargs.get('callback')893 broadcast = kwargs.get('broadcast')894 to = kwargs.pop('to', None) or kwargs.pop('room', None)895 if to is None and not broadcast:896 to = flask.request.sid897 include_self = kwargs.get('include_self', True)898 skip_sid = kwargs.get('skip_sid')899 ignore_queue = kwargs.get('ignore_queue', False)900 901 socketio = flask.current_app.extensions['socketio']902 return socketio.emit(event, *args, namespace=namespace, to=to,903 include_self=include_self, skip_sid=skip_sid,904 callback=callback, ignore_queue=ignore_queue)905 906 907def call(event, *args, **kwargs): # pragma: no cover908 """Emit a SocketIO event and wait for the response.909 910 This function issues an emit with a callback and waits for the callback to911 be invoked by the client before returning. If the callback isn’t invoked912 before the timeout, then a TimeoutError exception is raised. If the913 Socket.IO connection drops during the wait, this method still waits until914 the specified timeout. Example::915 916 def get_status(client, data):917 status = call('status', {'data': data}, to=client)918 919 :param event: The name of the user event to emit.920 :param args: A dictionary with the JSON data to send as payload.921 :param namespace: The namespace under which the message is to be sent.922 Defaults to the namespace used by the originating event.923 A ``'/'`` can be used to explicitly specify the global924 namespace.925 :param to: The session ID of the recipient client. If this argument is not926 given, the event is sent to the originating client.927 :param timeout: The waiting timeout. If the timeout is reached before the928 client acknowledges the event, then a ``TimeoutError``929 exception is raised. The default is 60 seconds.930 :param ignore_queue: Only used when a message queue is configured. If931 set to ``True``, the event is emitted to the932 client directly, without going through the queue.933 This is more efficient, but only works when a934 single server process is used, or when there is a935 single addressee. It is recommended to always leave936 this parameter with its default value of ``False``.937 """938 if 'namespace' in kwargs:939 namespace = kwargs['namespace']940 else:941 namespace = flask.request.namespace942 to = kwargs.pop('to', None) or kwargs.pop('room', None)943 if to is None:944 to = flask.request.sid945 timeout = kwargs.get('timeout', 60)946 ignore_queue = kwargs.get('ignore_queue', False)947 948 socketio = flask.current_app.extensions['socketio']949 return socketio.call(event, *args, namespace=namespace, to=to,950 ignore_queue=ignore_queue, timeout=timeout)951 952 953def send(message, **kwargs):954 """Send a SocketIO message.955 956 This function sends a simple SocketIO message to one or more connected957 clients. The message can be a string or a JSON blob. This is a simpler958 version of ``emit()``, which should be preferred. This is a function that959 can only be called from a SocketIO event handler.960 961 :param message: The message to send, either a string or a JSON blob.962 :param json: ``True`` if ``message`` is a JSON blob, ``False``963 otherwise.964 :param namespace: The namespace under which the message is to be sent.965 Defaults to the namespace used by the originating event.966 An empty string can be used to use the global namespace.967 :param callback: Callback function to invoke with the client's968 acknowledgement.969 :param broadcast: ``True`` to send the message to all connected clients, or970 ``False`` to only reply to the sender of the originating971 event.972 :param to: Send the message to all the users in the given room, or to the973 user with the given session ID. If this argument is not set and974 ``broadcast`` is ``False``, then the message is sent only to the975 originating user.976 :param include_self: ``True`` to include the sender when broadcasting or977 addressing a room, or ``False`` to send to everyone978 but the sender.979 :param skip_sid: The session id of a client to ignore when broadcasting980 or addressing a room. This is typically set to the981 originator of the message, so that everyone except982 that client receive the message. To skip multiple sids983 pass a list.984 :param ignore_queue: Only used when a message queue is configured. If985 set to ``True``, the event is emitted to the986 clients directly, without going through the queue.987 This is more efficient, but only works when a988 single server process is used, or when there is a989 single addressee. It is recommended to always leave990 this parameter with its default value of ``False``.991 """992 json = kwargs.get('json', False)993 if 'namespace' in kwargs:994 namespace = kwargs['namespace']995 else:996 namespace = flask.request.namespace997 callback = kwargs.get('callback')998 broadcast = kwargs.get('broadcast')999 to = kwargs.pop('to', None) or kwargs.pop('room', None)1000 if to is None and not broadcast:1001 to = flask.request.sid1002 include_self = kwargs.get('include_self', True)1003 skip_sid = kwargs.get('skip_sid')1004 ignore_queue = kwargs.get('ignore_queue', False)1005 1006 socketio = flask.current_app.extensions['socketio']1007 return socketio.send(message, json=json, namespace=namespace, to=to,1008 include_self=include_self, skip_sid=skip_sid,1009 callback=callback, ignore_queue=ignore_queue)1010 1011 1012def join_room(room, sid=None, namespace=None):1013 """Join a room.1014 1015 This function puts the user in a room, under the current namespace. The1016 user and the namespace are obtained from the event context. This is a1017 function that can only be called from a SocketIO event handler. Example::1018 1019 @socketio.on('join')1020 def on_join(data):1021 username = session['username']1022 room = data['room']1023 join_room(room)1024 send(username + ' has entered the room.', to=room)1025 1026 :param room: The name of the room to join.1027 :param sid: The session id of the client. If not provided, the client is1028 obtained from the request context.1029 :param namespace: The namespace for the room. If not provided, the1030 namespace is obtained from the request context.1031 """1032 socketio = flask.current_app.extensions['socketio']1033 sid = sid or flask.request.sid1034 namespace = namespace or flask.request.namespace1035 socketio.server.enter_room(sid, room, namespace=namespace)1036 1037 1038def leave_room(room, sid=None, namespace=None):1039 """Leave a room.1040 1041 This function removes the user from a room, under the current namespace.1042 The user and the namespace are obtained from the event context. Example::1043 1044 @socketio.on('leave')1045 def on_leave(data):1046 username = session['username']1047 room = data['room']1048 leave_room(room)1049 send(username + ' has left the room.', to=room)1050 1051 :param room: The name of the room to leave.1052 :param sid: The session id of the client. If not provided, the client is1053 obtained from the request context.1054 :param namespace: The namespace for the room. If not provided, the1055 namespace is obtained from the request context.1056 """1057 socketio = flask.current_app.extensions['socketio']1058 sid = sid or flask.request.sid1059 namespace = namespace or flask.request.namespace1060 socketio.server.leave_room(sid, room, namespace=namespace)1061 1062 1063def close_room(room, namespace=None):1064 """Close a room.1065 1066 This function removes any users that are in the given room and then deletes1067 the room from the server.1068 1069 :param room: The name of the room to close.1070 :param namespace: The namespace for the room. If not provided, the1071 namespace is obtained from the request context.1072 """1073 socketio = flask.current_app.extensions['socketio']1074 namespace = namespace or flask.request.namespace1075 socketio.server.close_room(room, namespace=namespace)1076 1077 1078def rooms(sid=None, namespace=None):1079 """Return a list of the rooms the client is in.1080 1081 This function returns all the rooms the client has entered, including its1082 own room, assigned by the Socket.IO server.1083 1084 :param sid: The session id of the client. If not provided, the client is1085 obtained from the request context.1086 :param namespace: The namespace for the room. If not provided, the1087 namespace is obtained from the request context.1088 """1089 socketio = flask.current_app.extensions['socketio']1090 sid = sid or flask.request.sid1091 namespace = namespace or flask.request.namespace1092 return socketio.server.rooms(sid, namespace=namespace)1093 1094 1095def disconnect(sid=None, namespace=None, silent=False):1096 """Disconnect the client.1097 1098 This function terminates the connection with the client. As a result of1099 this call the client will receive a disconnect event. Example::1100 1101 @socketio.on('message')1102 def receive_message(msg):1103 if is_banned(session['username']):1104 disconnect()1105 else:1106 # ...1107 1108 :param sid: The session id of the client. If not provided, the client is1109 obtained from the request context.1110 :param namespace: The namespace for the room. If not provided, the1111 namespace is obtained from the request context.1112 :param silent: this option is deprecated.1113 """1114 socketio = flask.current_app.extensions['socketio']1115 sid = sid or flask.request.sid1116 namespace = namespace or flask.request.namespace1117 return socketio.server.disconnect(sid, namespace=namespace)1118 