././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1736192976.7210176 flask_socketio-5.5.1/0000775000175000017500000000000014737031721014117 5ustar00miguelmiguel././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1730029461.0 flask_socketio-5.5.1/LICENSE0000664000175000017500000000207214707423625015132 0ustar00miguelmiguelThe MIT License (MIT) Copyright (c) 2014 Miguel Grinberg Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1730029461.0 flask_socketio-5.5.1/MANIFEST.in0000664000175000017500000000022714707423625015663 0ustar00miguelmiguelinclude README.md LICENSE tox.ini test_socketio.py recursive-include docs * recursive-exclude docs/_build * recursive-include tests * exclude **/*.pyc ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1736192976.7210176 flask_socketio-5.5.1/PKG-INFO0000644000175000017500000000511314737031721015212 0ustar00miguelmiguelMetadata-Version: 2.1 Name: Flask-SocketIO Version: 5.5.1 Summary: Socket.IO integration for Flask applications Author-email: Miguel Grinberg Project-URL: Homepage, https://github.com/miguelgrinberg/flask-socketio Project-URL: Bug Tracker, https://github.com/miguelgrinberg/flask-socketio/issues Classifier: Environment :: Web Environment Classifier: Intended Audience :: Developers Classifier: Programming Language :: Python :: 3 Classifier: License :: OSI Approved :: MIT License Classifier: Operating System :: OS Independent Requires-Python: >=3.6 Description-Content-Type: text/markdown License-File: LICENSE Requires-Dist: Flask>=0.9 Requires-Dist: python-socketio>=5.12.0 Provides-Extra: docs Requires-Dist: sphinx; extra == "docs" Flask-SocketIO ============== [![Build status](https://github.com/miguelgrinberg/flask-socketio/workflows/build/badge.svg)](https://github.com/miguelgrinberg/Flask-SocketIO/actions) [![codecov](https://codecov.io/gh/miguelgrinberg/flask-socketio/branch/main/graph/badge.svg)](https://codecov.io/gh/miguelgrinberg/flask-socketio) Socket.IO integration for Flask applications. Sponsors -------- The following organizations are funding this project: ![Socket.IO](https://images.opencollective.com/socketio/050e5eb/logo/64.png)
[Socket.IO](https://socket.io) | [Add your company here!](https://github.com/sponsors/miguelgrinberg)| -|- Many individual sponsors also support this project through small ongoing contributions. Why not [join them](https://github.com/sponsors/miguelgrinberg)? Installation ------------ You can install this package as usual with pip: pip install flask-socketio Example ------- ```py from flask import Flask, render_template from flask_socketio import SocketIO, emit app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app) @app.route('/') def index(): return render_template('index.html') @socketio.event def my_event(message): emit('my response', {'data': 'got it!'}) if __name__ == '__main__': socketio.run(app) ``` Resources --------- - [Tutorial](http://blog.miguelgrinberg.com/post/easy-websockets-with-flask-and-gevent) - [Documentation](http://flask-socketio.readthedocs.io/en/latest/) - [PyPI](https://pypi.python.org/pypi/Flask-SocketIO) - [Change Log](https://github.com/miguelgrinberg/Flask-SocketIO/blob/main/CHANGES.md) - Questions? See the [questions](https://stackoverflow.com/questions/tagged/flask-socketio) others have asked on Stack Overflow, or [ask](https://stackoverflow.com/questions/ask?tags=python+flask-socketio+python-socketio) your own question. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1730029461.0 flask_socketio-5.5.1/README.md0000664000175000017500000000351314707423625015405 0ustar00miguelmiguelFlask-SocketIO ============== [![Build status](https://github.com/miguelgrinberg/flask-socketio/workflows/build/badge.svg)](https://github.com/miguelgrinberg/Flask-SocketIO/actions) [![codecov](https://codecov.io/gh/miguelgrinberg/flask-socketio/branch/main/graph/badge.svg)](https://codecov.io/gh/miguelgrinberg/flask-socketio) Socket.IO integration for Flask applications. Sponsors -------- The following organizations are funding this project: ![Socket.IO](https://images.opencollective.com/socketio/050e5eb/logo/64.png)
[Socket.IO](https://socket.io) | [Add your company here!](https://github.com/sponsors/miguelgrinberg)| -|- Many individual sponsors also support this project through small ongoing contributions. Why not [join them](https://github.com/sponsors/miguelgrinberg)? Installation ------------ You can install this package as usual with pip: pip install flask-socketio Example ------- ```py from flask import Flask, render_template from flask_socketio import SocketIO, emit app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app) @app.route('/') def index(): return render_template('index.html') @socketio.event def my_event(message): emit('my response', {'data': 'got it!'}) if __name__ == '__main__': socketio.run(app) ``` Resources --------- - [Tutorial](http://blog.miguelgrinberg.com/post/easy-websockets-with-flask-and-gevent) - [Documentation](http://flask-socketio.readthedocs.io/en/latest/) - [PyPI](https://pypi.python.org/pypi/Flask-SocketIO) - [Change Log](https://github.com/miguelgrinberg/Flask-SocketIO/blob/main/CHANGES.md) - Questions? See the [questions](https://stackoverflow.com/questions/tagged/flask-socketio) others have asked on Stack Overflow, or [ask](https://stackoverflow.com/questions/ask?tags=python+flask-socketio+python-socketio) your own question. ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1736192976.7190175 flask_socketio-5.5.1/docs/0000775000175000017500000000000014737031721015047 5ustar00miguelmiguel././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1730029461.0 flask_socketio-5.5.1/docs/Makefile0000664000175000017500000000110414707423625016510 0ustar00miguelmiguel# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build SOURCEDIR = . BUILDDIR = _build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1736192976.7190175 flask_socketio-5.5.1/docs/_static/0000775000175000017500000000000014737031721016475 5ustar00miguelmiguel././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1730029461.0 flask_socketio-5.5.1/docs/_static/README.md0000664000175000017500000000006314707423625017760 0ustar00miguelmiguelPlace static files used by the documentation here. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1730029461.0 flask_socketio-5.5.1/docs/_static/custom.css0000664000175000017500000000013614707423625020526 0ustar00miguelmigueldiv.sphinxsidebar { max-height: calc(100% - 30px); overflow-y: auto; overflow-x: hidden; } ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1730029461.0 flask_socketio-5.5.1/docs/api.rst0000664000175000017500000000055314707423625016362 0ustar00miguelmiguelAPI Reference ============= .. module:: flask_socketio .. autoclass:: SocketIO :members: .. autofunction:: emit .. autofunction:: send .. autofunction:: join_room .. autofunction:: leave_room .. autofunction:: close_room .. autofunction:: rooms .. autofunction:: disconnect .. autoclass:: Namespace :members: .. autoclass:: SocketIOTestClient :members: ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1730029461.0 flask_socketio-5.5.1/docs/conf.py0000664000175000017500000001262514707423625016361 0ustar00miguelmiguel# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) # -- Project information ----------------------------------------------------- project = 'Flask-SocketIO' copyright = '2018, Miguel Grinberg' author = 'Miguel Grinberg' # The short X.Y version version = '' # The full version, including alpha/beta/rc tags release = '' # -- General configuration --------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', ] autodoc_member_order = 'bysource' # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = None # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = { 'github_user': 'miguelgrinberg', 'github_repo': 'flask-socketio', 'github_banner': True, 'github_button': True, 'github_type': 'star', 'fixed_sidebar': True, } # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # The default sidebars (for documents that don't match any pattern) are # defined by theme itself. Builtin themes are using these templates by # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', # 'searchbox.html']``. # # html_sidebars = {} # -- Options for HTMLHelp output --------------------------------------------- # Output file base name for HTML help builder. htmlhelp_basename = 'flask-socketiodoc' # -- Options for LaTeX output ------------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'flask-socketio.tex', 'flask-socketio Documentation', 'Miguel Grinberg', 'manual'), ] # -- Options for manual page output ------------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'flask-socketio', 'flask-socketio Documentation', [author], 1) ] # -- Options for Texinfo output ---------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'flask-socketio', 'flask-socketio Documentation', author, 'flask-socketio', 'One line description of project.', 'Miscellaneous'), ] # -- Options for Epub output ------------------------------------------------- # Bibliographic Dublin Core info. epub_title = project # The unique identifier of the text. This can be a ISBN number # or the project homepage. # # epub_identifier = '' # A unique identification for the text. # # epub_uid = '' # A list of files that should not be packed into the epub file. epub_exclude_files = ['search.html'] # -- Extension configuration ------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734028986.0 flask_socketio-5.5.1/docs/deployment.rst0000664000175000017500000002605014726627272017776 0ustar00miguelmiguelDeployment ---------- There are many options to deploy a Flask-SocketIO server, ranging from simple to the insanely complex. In this section, the most commonly used options are described. Embedded Server ~~~~~~~~~~~~~~~ The simplest deployment strategy is to start the web server by calling ``socketio.run(app)`` as shown in examples above. This will look through the packages that are installed for the best available web server and start the application on it. The current web server choices that are evaluated are ``eventlet``, ``gevent`` and the Flask development server. If eventlet or gevent are available, ``socketio.run(app)`` starts a production-ready server using one of these frameworks. If neither of these are installed, then the Flask development web server is used, and in this case the server is not intended to be used in a production deployment. Unfortunately this option is not available when using gevent with uWSGI. See the uWSGI section below for information on this option. Gunicorn Web Server ~~~~~~~~~~~~~~~~~~~ An alternative to ``socketio.run(app)`` is to use `gunicorn `_ as web server, using the eventlet or gevent workers. For this option, eventlet or gevent need to be installed, in addition to gunicorn. The command line that starts the eventlet server via gunicorn is:: gunicorn --worker-class eventlet -w 1 module:app If you prefer to use gevent, the command to start the server is:: gunicorn -k gevent -w 1 module:app When using gunicorn with the gevent worker and the WebSocket support provided by gevent-websocket, the command that starts the server must be changed to select a custom gevent web server that supports the WebSocket protocol. The modified command is:: gunicorn -k geventwebsocket.gunicorn.workers.GeventWebSocketWorker -w 1 module:app A third option with Gunicorn is to use the threaded worker, along with the `simple-websocket `_ package for WebSocket support. This is a particularly good solution for applications that are CPU heavy or are otherwise incompatible with eventlet and gevent use of green threads. The command to start a threaded web server is:: gunicorn -w 1 --threads 100 module:app In all these commands, ``module`` is the Python module or package that defines the application instance, and ``app`` is the application instance itself. Due to the limited load balancing algorithm used by gunicorn, it is not possible to use more than one worker process when using this web server. For that reason, all the examples above include the ``-w 1`` option. The workaround to use multiple worker processes with gunicorn is to launch several single-worker instances and put them behind a more capable load balancer such as `nginx `_. uWSGI Web Server ~~~~~~~~~~~~~~~~ When using the uWSGI server in combination with gevent, the Socket.IO server can take advantage of uWSGI’s native WebSocket support. A complete explanation of the configuration and usage of the uWSGI server is beyond the scope of this documentation. The uWSGI server is a fairly complex package that provides a large and comprehensive set of options. It must be compiled with WebSocket and SSL support for the WebSocket transport to be available. As way of an introduction, the following command starts a uWSGI server for the example application app.py on port 5000:: $ uwsgi --http :5000 --gevent 1000 --http-websockets --master --wsgi-file app.py --callable app Using nginx as a WebSocket Reverse Proxy ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It is possible to use nginx as a front-end reverse proxy that passes requests to the application. However, only releases of nginx 1.4 and newer support proxying of the WebSocket protocol. Below is a basic nginx configuration that proxies HTTP and WebSocket requests:: server { listen 80; server_name _; location / { include proxy_params; proxy_pass http://127.0.0.1:5000; } location /static/ { alias /static/; expires 30d; } location /socket.io { include proxy_params; proxy_http_version 1.1; proxy_buffering off; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_pass http://127.0.0.1:5000/socket.io; } } The next example adds the support for load balancing multiple Socket.IO servers:: upstream socketio_nodes { ip_hash; server 127.0.0.1:5000; server 127.0.0.1:5001; server 127.0.0.1:5002; # to scale the app, just add more nodes here! } server { listen 80; server_name _; location / { include proxy_params; proxy_pass http://127.0.0.1:5000; } location /static/ { alias /static/; expires 30d; } location /socket.io { include proxy_params; proxy_http_version 1.1; proxy_buffering off; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_pass http://socketio_nodes/socket.io; } } While the above examples can work as an initial configuration, be aware that a production install of nginx will need a more complete configuration covering other deployment aspects such as SSL support. Using Multiple Workers ~~~~~~~~~~~~~~~~~~~~~~ Flask-SocketIO supports multiple workers behind a load balancer starting with release 2.0. Deploying multiple workers gives applications that use Flask-SocketIO the ability to spread the client connections among multiple processes and hosts, and in this way scale to support very large numbers of concurrent clients. There are two requirements to use multiple Flask-SocketIO workers: - The load balancer must be configured to forward all HTTP requests from a given client always to the same worker. This is sometimes referenced as "sticky sessions". For nginx, use the ``ip_hash`` directive to achieve this. Gunicorn cannot be used with multiple workers because its load balancer algorithm does not support sticky sessions. - Since each of the servers owns only a subset of the client connections, a message queue such as Redis or RabbitMQ is used by the servers to coordinate complex operations such as broadcasting and rooms. When working with a message queue, there are additional dependencies that need to be installed: - For Redis, the package ``redis`` must be installed (``pip install redis``). - For RabbitMQ, the package ``kombu`` must be installed (``pip install kombu``). - For Kafka, the package ``kafka-python`` must be installed (``pip install kafka-python``). - For other message queues supported by Kombu, see the `Kombu documentation `_ to find out what dependencies are needed. - If eventlet or gevent are used, then monkey patching the Python standard library is normally required to force the message queue package to use coroutine friendly functions and classes. For eventlet, monkey patching is done with:: import eventlet eventlet.monkey_patch() For gevent, you can monkey patch the standard library with:: from gevent import monkey monkey.patch_all() In both cases it is recommended that you apply the monkey patching at the top of your main script, even above your imports. To start multiple Flask-SocketIO servers, you must first ensure you have the message queue service running. To start a Socket.IO server and have it connect to the message queue, add the ``message_queue`` argument to the ``SocketIO`` constructor:: socketio = SocketIO(app, message_queue='redis://') The value of the ``message_queue`` argument is the connection URL of the queue service that is used. For a redis queue running on the same host as the server, the ``'redis://'`` URL can be used. Likewise, for a default RabbitMQ queue the ``'amqp://'`` URL can be used. For Kafka, use a ``kafka://`` URL. The Kombu package has a `documentation section `_ that describes the format of the URLs for all the supported queues. Emitting from an External Process ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For many types of applications, it is necessary to emit events from a process that is not the SocketIO server, for an example a Celery worker. If the SocketIO server or servers are configured to listen on a message queue as shown in the previous section, then any other process can create its own ``SocketIO`` instance and use it to emit events in the same way the server does. For example, for an application that runs on an eventlet web server and uses a Redis message queue, the following Python script broadcasts an event to all clients:: socketio = SocketIO(message_queue='redis://') socketio.emit('my event', {'data': 'foo'}, namespace='/test') When using the ``SocketIO`` instance in this way, the Flask application instance is not passed to the constructor. The ``channel`` argument to ``SocketIO`` can be used to select a specific channel of communication through the message queue. Using a custom channel name is necessary when there are multiple independent SocketIO services sharing the same queue. Flask-SocketIO does not apply monkey patching when eventlet or gevent are used. But when working with a message queue, it is very likely that the Python package that talks to the message queue service will hang if the Python standard library is not monkey patched. It is important to note that an external process that wants to connect to a SocketIO server does not need to use eventlet or gevent like the main server. Having a server use a coroutine framework, while an external process is not a problem. For example, Celery workers do not need to be configured to use eventlet or gevent just because the main server does. But if your external process does use a coroutine framework for whatever reason, then monkey patching is likely required, so that the message queue accesses coroutine friendly functions and classes. Cross-Origin Controls ~~~~~~~~~~~~~~~~~~~~~ For security reasons, this server enforces a same-origin policy by default. In practical terms, this means the following: - If an incoming HTTP or WebSocket request includes the ``Origin`` header, this header must match the scheme and host of the connection URL. In case of a mismatch, a 400 status code response is returned and the connection is rejected. - No restrictions are imposed on incoming requests that do not include the ``Origin`` header. If necessary, the ``cors_allowed_origins`` option can be used to allow other origins. This argument can be set to a string to set a single allowed origin, or to a list to allow multiple origins. A special value of ``'*'`` can be used to instruct the server to allow all origins, but this should be done with care, as this could make the server vulnerable to Cross-Site Request Forgery (CSRF) attacks. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734545228.0 flask_socketio-5.5.1/docs/getting_started.rst0000664000175000017500000003437614730607514021007 0ustar00miguelmiguelGetting Started =============== Initialization -------------- The following code example shows how to add Flask-SocketIO to a Flask application:: from flask import Flask, render_template from flask_socketio import SocketIO app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app) if __name__ == '__main__': socketio.run(app) The ``init_app()`` style of initialization is also supported. To start the web server simply execute your script. Note the way the web server is started. The ``socketio.run()`` function encapsulates the start up of the web server and replaces the ``app.run()`` standard Flask development server start up. When the application is in debug mode the Werkzeug development server is still used and configured properly inside ``socketio.run()``. In production mode the eventlet web server is used if available, else the gevent web server is used. If eventlet and gevent are not installed, the Werkzeug development web server is used. The ``flask run`` command introduced in Flask 0.11 can be used to start a Flask-SocketIO development server based on Werkzeug, but this method of starting the Flask-SocketIO server is not recommended due to lack of WebSocket support. Previous versions of this package included a customized version of the ``flask run`` command that allowed the use of WebSocket on eventlet and gevent production servers, but this functionality has been discontinued in favor of the ``socketio.run(app)`` startup method shown above which is more robust. The application must serve a page to the client that loads the Socket.IO library and establishes a connection:: Receiving Messages ------------------ When using SocketIO, messages are received by both parties as events. On the client side Javascript callbacks are used. With Flask-SocketIO the server needs to register handlers for these events, similarly to how routes are handled by view functions. The following example creates a server-side event handler for an unnamed event:: @socketio.on('message') def handle_message(data): print('received message: ' + data) The above example uses string messages. Another type of unnamed events use JSON data:: @socketio.on('json') def handle_json(json): print('received json: ' + str(json)) The most flexible type of event uses custom event names. The message data for these events can be string, bytes, int, or JSON:: @socketio.on('my event') def handle_my_custom_event(json): print('received json: ' + str(json)) Custom named events can also support multiple arguments:: @socketio.on('my_event') def handle_my_custom_event(arg1, arg2, arg3): print('received args: ' + arg1 + arg2 + arg3) When the name of the event is a valid Python identifier that does not collide with other defined symbols, the ``@socketio.event`` decorator provides a more compact syntax that takes the event name from the decorated function:: @socketio.event def my_custom_event(arg1, arg2, arg3): print('received args: ' + arg1 + arg2 + arg3) Named events are the most flexible, as they eliminate the need to include additional metadata to describe the message type. The names ``message``, ``json``, ``connect`` and ``disconnect`` are reserved and cannot be used for named events. Flask-SocketIO also supports SocketIO namespaces, which allow the client to multiplex several independent connections on the same physical socket:: @socketio.on('my event', namespace='/test') def handle_my_custom_namespace_event(json): print('received json: ' + str(json)) When a namespace is not specified a default global namespace with the name ``'/'`` is used. For cases when a decorator syntax isn't convenient, the ``on_event`` method can be used:: def my_function_handler(data): pass socketio.on_event('my event', my_function_handler, namespace='/test') Clients may request an acknowledgement callback that confirms receipt of a message they sent. Any values returned from the handler function will be passed to the client as arguments in the callback function:: @socketio.on('my event') def handle_my_custom_event(json): print('received json: ' + str(json)) return 'one', 2 In the above example, the client callback function will be invoked with two arguments, ``'one'`` and ``2``. If a handler function does not return any values, the client callback function will be invoked without arguments. Sending Messages ---------------- SocketIO event handlers defined as shown in the previous section can send reply messages to the connected client using the ``send()`` and ``emit()`` functions. The following examples bounce received events back to the client that sent them:: from flask_socketio import send, emit @socketio.on('message') def handle_message(message): send(message) @socketio.on('json') def handle_json(json): send(json, json=True) @socketio.on('my event') def handle_my_custom_event(json): emit('my response', json) Note how ``send()`` and ``emit()`` are used for unnamed and named events respectively. When working with namespaces, ``send()`` and ``emit()`` use the namespace of the incoming message by default. A different namespace can be specified with the optional ``namespace`` argument:: @socketio.on('message') def handle_message(message): send(message, namespace='/chat') @socketio.on('my event') def handle_my_custom_event(json): emit('my response', json, namespace='/chat') To send an event with multiple arguments, send a tuple:: @socketio.on('my event') def handle_my_custom_event(json): emit('my response', ('foo', 'bar', json), namespace='/chat') SocketIO supports acknowledgment callbacks that confirm that a message was received by the client:: def ack(): print('message was received!') @socketio.on('my event') def handle_my_custom_event(json): emit('my response', json, callback=ack) When using callbacks, the Javascript client receives a callback function to invoke upon receipt of the message. After the client application invokes the callback function the server invokes the corresponding server-side callback. If the client-side callback is invoked with arguments, these are provided as arguments to the server-side callback as well. Broadcasting ------------ Another very useful feature of SocketIO is the broadcasting of messages. Flask-SocketIO supports this feature with the ``broadcast=True`` optional argument to ``send()`` and ``emit()``:: @socketio.on('my event') def handle_my_custom_event(data): emit('my response', data, broadcast=True) When a message is sent with the broadcast option enabled, all clients connected to the namespace receive it, including the sender. When namespaces are not used, the clients connected to the global namespace receive the message. Note that callbacks are not invoked for broadcast messages. In all the examples shown until this point the server responds to an event sent by the client. But for some applications, the server needs to be the originator of a message. This can be useful to send notifications to clients of events that originated in the server, for example in a background thread. The ``socketio.send()`` and ``socketio.emit()`` methods can be used to broadcast to all connected clients:: def some_function(): socketio.emit('some event', {'data': 42}) Note that ``socketio.send()`` and ``socketio.emit()`` are not the same functions as the context-aware ``send()`` and ``emit()``. Also note that in the above usage there is no client context, so ``broadcast=True`` is assumed and does not need to be specified. Rooms ----- For many applications it is necessary to group users into subsets that can be addressed together. The best example is a chat application with multiple rooms, where users receive messages from the room or rooms they are in, but not from other rooms where other users are. Flask-SocketIO supports this concept of rooms through the ``join_room()`` and ``leave_room()`` functions:: from flask_socketio import join_room, leave_room @socketio.on('join') def on_join(data): username = data['username'] room = data['room'] join_room(room) send(username + ' has entered the room.', to=room) @socketio.on('leave') def on_leave(data): username = data['username'] room = data['room'] leave_room(room) send(username + ' has left the room.', to=room) The ``send()`` and ``emit()`` functions accept an optional ``to`` argument that cause the message to be sent to all the clients that are in the given room. All clients are assigned a room when they connect, named with the session ID of the connection, which can be obtained from ``request.sid``. A given client can join any rooms, which can be given any names. When a client disconnects it is removed from all the rooms it was in. The context-free ``socketio.send()`` and ``socketio.emit()`` functions also accept a ``to`` argument to broadcast to all clients in a room. Since all clients are assigned a personal room, to address a message to a single client, the session ID of the client can be used as the ``to`` argument. Connection Events ----------------- Flask-SocketIO also dispatches connection and disconnection events. The following example shows how to register handlers for them:: @socketio.on('connect') def test_connect(auth): emit('my response', {'data': 'Connected'}) @socketio.on('disconnect') def test_disconnect(reason): print('Client disconnected, reason:', reason) The ``auth`` argument in the connection handler is optional. The client can use it to pass authentication data such as tokens in dictionary format. If the client does not provide authentication details, then this argument is set to ``None``. If the server defines a connection event handler without this argument, then any authentication data passed by the client is discarded. The connection event handler can return ``False`` to reject the connection, or it can also raise `ConnectionRefusedError`. This is so that the client can be authenticated at this point. When using the exception, any arguments passed to the exception are returned to the client in the error packet. Examples:: from flask_socketio import ConnectionRefusedError @socketio.on('connect') def connect(): if not self.authenticate(request.args): raise ConnectionRefusedError('unauthorized!') The disconnection event handler receives a ``reason`` argument that indicates the cause of the disconnection. The :attr:`flask_socketio.SocketIO.reason` member includes constants for all the possible reasons. Note that connection and disconnection events are sent individually on each namespace used. Class-Based Namespaces ---------------------- As an alternative to the decorator-based event handlers described above, the event handlers that belong to a namespace can be created as methods of a class. The :class:`flask_socketio.Namespace` is provided as a base class to create class-based namespaces:: from flask_socketio import Namespace, emit class MyCustomNamespace(Namespace): def on_connect(self): pass def on_disconnect(self, reason): pass def on_my_event(self, data): emit('my_response', data) socketio.on_namespace(MyCustomNamespace('/test')) When class-based namespaces are used, any events received by the server are dispatched to a method named as the event name with the ``on_`` prefix. For example, event ``my_event`` will be handled by a method named ``on_my_event``. If an event is received for which there is no corresponding method defined in the namespace class, then the event is ignored. All event names used in class-based namespaces must use characters that are legal in method names. As a convenience to methods defined in a class-based namespace, the namespace instance includes versions of several of the methods in the :class:`flask_socketio.SocketIO` class that default to the proper namespace when the ``namespace`` argument is not given. If an event has a handler in a class-based namespace, and also a decorator-based function handler, only the decorated function handler is invoked. Error Handling -------------- Flask-SocketIO can also deal with exceptions:: @socketio.on_error() # Handles the default namespace def error_handler(e): pass @socketio.on_error('/chat') # handles the '/chat' namespace def error_handler_chat(e): pass @socketio.on_error_default # handles all namespaces without an explicit error handler def default_error_handler(e): pass Error handler functions take the exception object as an argument. The message and data arguments of the current request can also be inspected with the ``request.event`` variable, which is useful for error logging and debugging outside the event handler:: from flask import request @socketio.on("my error event") def on_my_event(data): raise RuntimeError() @socketio.on_error_default def default_error_handler(e): print(request.event["message"]) # "my error event" print(request.event["args"]) # (data,) Debugging and Troubleshooting ----------------------------- To help you debug issues, the server can be configured to output logs to the terminal:: socketio = SocketIO(logger=True, engineio_logger=True) The ``logger`` argument controls logging related to the Socket.IO protocol, while ``engineio_logger`` controls logs that originate in the low-level Engine.IO transport. These arguments can be set to ``True`` to output logs to ``stderr``, or to an object compatible with Python's ``logging`` package where the logs should be emitted to. A value of ``False`` disables logging. Logging can help identify the cause of connection problems, 400 responses, bad performance and other issues. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1730029461.0 flask_socketio-5.5.1/docs/implementation_notes.rst0000664000175000017500000001264314707423625022051 0ustar00miguelmiguelImplementation Notes ==================== Access to Flask's Context Globals --------------------------------- Handlers for SocketIO events are different than handlers for routes and that introduces a lot of confusion around what can and cannot be done in a SocketIO handler. The main difference is that all the SocketIO events generated for a client occur in the context of a single long running request. In spite of the differences, Flask-SocketIO attempts to make working with SocketIO event handlers easier by making the environment similar to that of a regular HTTP request. The following list describes what works and what doesn't: - An application context is pushed before invoking an event handler making ``current_app`` and ``g`` available to the handler. - A request context is also pushed before invoking a handler, also making ``request`` and ``session`` available. But note that WebSocket events do not have individual requests associated with them, so the request context that started the connection is pushed for all the events that are dispatched during the life of the connection. - The ``request`` context global is enhanced with a ``sid`` member that is set to a unique session ID for the connection. This value is used as an initial room where the client is added. - The ``request`` context global is enhanced with ``namespace`` and ``event`` members that contain the currently handled namespace and event arguments. The ``event`` member is a dictionary with ``message`` and ``args`` keys. - The ``session`` context global behaves in a different way than in regular requests. A copy of the user session at the time the SocketIO connection is established is made available to handlers invoked in the context of that connection. If a SocketIO handler modifies the session, the modified session will be preserved for future SocketIO handlers, but regular HTTP route handlers will not see these changes. Effectively, when a SocketIO handler modifies the session, a "fork" of the session is created exclusively for these handlers. The technical reason for this limitation is that to save the user session a cookie needs to be sent to the client, and that requires HTTP request and response, which do not exist in a SocketIO connection. When using server-side sessions such as those provided by the Flask-Session or Flask-KVSession extensions, changes made to the session in HTTP route handlers can be seen by SocketIO handlers, as long as the session is not modified in the SocketIO handlers. - The ``before_request`` and ``after_request`` hooks are not invoked for SocketIO event handlers. - SocketIO handlers can take custom decorators, but most Flask decorators will not be appropriate to use for a SocketIO handler, given that there is no concept of a ``Response`` object during a SocketIO connection. Authentication -------------- A common need of applications is to validate the identity of their users. The traditional mechanisms based on web forms and HTTP requests cannot be used in a SocketIO connection, since there is no place to send HTTP requests and responses. If necessary, an application can implement a customized login form that sends credentials to the server as a SocketIO message when the submit button is pressed by the user. However, in most cases it is more convenient to perform the traditional authentication process before the SocketIO connection is established. The user's identity can then be recorded in the user session or in a cookie, and later when the SocketIO connection is established that information will be accessible to SocketIO event handlers. Recent revisions of the Socket.IO protocol include the ability to pass a dictionary with authentication information during the connection. This is an ideal place for the client to include a token or other authentication details. If the client uses this capability, the server will provide this dictionary as an argument to the ``connect`` event handler, as shown above. Using Flask-Login with Flask-SocketIO ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Flask-SocketIO can access login information maintained by `Flask-Login `_. After a regular Flask-Login authentication is performed and the ``login_user()`` function is called to record the user in the user session, any SocketIO connections will have access to the ``current_user`` context variable:: @socketio.on('connect') def connect_handler(): if current_user.is_authenticated: emit('my response', {'message': '{0} has joined'.format(current_user.name)}, broadcast=True) else: return False # not allowed here Note that the ``login_required`` decorator cannot be used with SocketIO event handlers, but a custom decorator that disconnects non-authenticated users can be created as follows:: import functools from flask import request from flask_login import current_user from flask_socketio import disconnect, emit def authenticated_only(f): @functools.wraps(f) def wrapped(*args, **kwargs): if not current_user.is_authenticated: disconnect() else: return f(*args, **kwargs) return wrapped @socketio.on('my event') @authenticated_only def handle_my_custom_event(data): emit('my response', {'message': '{0} has joined'.format(current_user.name)}, broadcast=True) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1730029461.0 flask_socketio-5.5.1/docs/index.rst0000664000175000017500000000141414707423625016715 0ustar00miguelmiguel.. flask-socketio documentation master file, created by sphinx-quickstart on Sun Nov 25 11:52:38 2018. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Flask-SocketIO =============== **Flask-SocketIO** gives Flask applications access to low latency bi-directional communications between the clients and the server. The client-side application can use any of the `SocketIO `_ client libraries in Javascript, Python, C++, Java and Swift, or any other compatible client to establish a permanent connection to the server. .. toctree:: :maxdepth: 3 intro getting_started implementation_notes deployment upgrading api * :ref:`genindex` * :ref:`modindex` * :ref:`search` ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1730029461.0 flask_socketio-5.5.1/docs/intro.rst0000664000175000017500000001064214707423625016744 0ustar00miguelmiguelIntroduction ============ Installation ------------ You can install this package in the usual way using ``pip``:: pip install flask-socketio Requirements ------------ Flask-SocketIO is compatible with Python 3.6+. The asynchronous services that this package relies on can be selected among three choices: - `eventlet `_ is the best performant option, with support for long-polling and WebSocket transports. - `gevent `_ is supported in a number of different configurations. The long-polling transport is fully supported with the gevent package, but unlike eventlet, gevent does not have native WebSocket support. To add support for WebSocket there are currently two options. Installing the `gevent-websocket `_ package adds WebSocket support to gevent or one can use the `uWSGI `_ web server, which comes with WebSocket functionality. The use of gevent is also a performant option, but slightly lower than eventlet. - The Flask development server based on Werkzeug can be used as well, with the caveat that this web server is intended only for development use, so it should only be used to simplify the development workflow and not for production. The extension automatically detects which asynchronous framework to use based on what is installed. Preference is given to eventlet, followed by gevent. For WebSocket support in gevent, uWSGI is preferred, followed by gevent-websocket. If neither eventlet nor gevent are installed, then the Flask development server is used. If using multiple processes, a message queue service must be configured to allow the servers to coordinate operations such as broadcasting. The supported queues are `Redis `_, `RabbitMQ `_, `Kafka `_, and any other message queues supported by the `Kombu `_ package. On the client-side, the official Socket.IO Javascript client library can be used to establish a connection to the server. There are also official clients written in Swift, Java and C++. Unofficial clients may also work, as long as they implement the `Socket.IO protocol `_. The `python-socketio `_ package (which provides the Socket.IO server implementation used by Flask-SocketIO) includes a Python client. Version compatibility --------------------- The Socket.IO protocol has been through a number of revisions, and some of these introduced backward incompatible changes, which means that the client and the server must use compatible versions for everything to work. The version compatibility chart below maps versions of this package to versions of the JavaScript reference implementation and the versions of the Socket.IO and Engine.IO protocols. +------------------------------+-----------------------------+-----------------------------+------------------------+-------------------------+-------------------------+ | JavaScript Socket.IO version | Socket.IO protocol revision | Engine.IO protocol revision | Flask-SocketIO version | python-socketio version | python-engineio version | +==============================+=============================+=============================+========================+=========================+=========================+ | 0.9.x | 1, 2 | 1, 2 | Not supported | Not supported | Not supported | +------------------------------+-----------------------------+-----------------------------+------------------------+-------------------------+-------------------------+ | 1.x and 2.x | 3, 4 | 3 | 4.x | 4.x | 3.x | +------------------------------+-----------------------------+-----------------------------+------------------------+-------------------------+-------------------------+ | 3.x and 4.x | 5 | 4 | 5.x | 5.x | 4.x | +------------------------------+-----------------------------+-----------------------------+------------------------+-------------------------+-------------------------+ ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1730029461.0 flask_socketio-5.5.1/docs/make.bat0000664000175000017500000000142314707423625016461 0ustar00miguelmiguel@ECHO OFF pushd %~dp0 REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set SOURCEDIR=. set BUILDDIR=_build if "%1" == "" goto help %SPHINXBUILD% >NUL 2>NUL if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% goto end :help %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% :end popd ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1730029461.0 flask_socketio-5.5.1/docs/upgrading.rst0000664000175000017500000000261014707423625017565 0ustar00miguelmiguelUpgrading to Flask-SocketIO 5.x from the 4.x releases ----------------------------------------------------- The Socket.IO protocol recently introduced a series of backwards incompatible changes. The 5.x releases of Flask-SocketIO adopted these changes, and for that reason it can only be used with clients that have also been updated to the current version of the protocol. In particular, this means that the JavaScript client must be upgraded to a 3.x release, and if your client hasn't been upgraded to the latest version of the Socket.IO protocol, then you must use a Flask-SocketIO 4.x release. The following protocol changes are of importance, as they may affect existing applications: - The default namespace ``'/'`` is not automatically connected anymore, and is now treated in the same way as other namespaces. - Each namespace connection has its own ``sid`` value, different from the others and different from the Engine.IO ``sid``. - Flask-SocketIO now uses the same ping interval and timeout values as the JavaScript reference implementation, which are 25 and 5 seconds respectively. - The ping/pong mechanism has been reversed. In the current version of the protocol, the server issues a ping and the client responds with a pong. - The default allowed payload size for long--polling packets has been lowered from 100MB to 1MB. - The `io` cookie is not sent to the client anymore by default. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1736192975.0 flask_socketio-5.5.1/pyproject.toml0000664000175000017500000000206414737031717017042 0ustar00miguelmiguel[project] name = "Flask-SocketIO" version = "5.5.1" authors = [ { name = "Miguel Grinberg", email = "miguel.grinberg@gmail.com" }, ] description = "Socket.IO integration for Flask applications" classifiers = [ "Environment :: Web Environment", "Intended Audience :: Developers", "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ] requires-python = ">=3.6" dependencies = [ "Flask >= 0.9", "python-socketio >= 5.12.0", ] [project.readme] file = "README.md" content-type = "text/markdown" [project.urls] Homepage = "https://github.com/miguelgrinberg/flask-socketio" "Bug Tracker" = "https://github.com/miguelgrinberg/flask-socketio/issues" [project.optional-dependencies] docs = [ "sphinx", ] [tool.setuptools] zip-safe = false include-package-data = true [tool.setuptools.package-dir] "" = "src" [tool.setuptools.packages.find] where = [ "src", ] namespaces = false [build-system] requires = [ "setuptools>=61.2", ] build-backend = "setuptools.build_meta" ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1736192976.7210176 flask_socketio-5.5.1/setup.cfg0000664000175000017500000000004614737031721015740 0ustar00miguelmiguel[egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1736192976.7170177 flask_socketio-5.5.1/src/0000775000175000017500000000000014737031721014706 5ustar00miguelmiguel././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1736192976.7210176 flask_socketio-5.5.1/src/Flask_SocketIO.egg-info/0000775000175000017500000000000014737031721021200 5ustar00miguelmiguel././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1736192976.0 flask_socketio-5.5.1/src/Flask_SocketIO.egg-info/PKG-INFO0000644000175000017500000000511314737031720022272 0ustar00miguelmiguelMetadata-Version: 2.1 Name: Flask-SocketIO Version: 5.5.1 Summary: Socket.IO integration for Flask applications Author-email: Miguel Grinberg Project-URL: Homepage, https://github.com/miguelgrinberg/flask-socketio Project-URL: Bug Tracker, https://github.com/miguelgrinberg/flask-socketio/issues Classifier: Environment :: Web Environment Classifier: Intended Audience :: Developers Classifier: Programming Language :: Python :: 3 Classifier: License :: OSI Approved :: MIT License Classifier: Operating System :: OS Independent Requires-Python: >=3.6 Description-Content-Type: text/markdown License-File: LICENSE Requires-Dist: Flask>=0.9 Requires-Dist: python-socketio>=5.12.0 Provides-Extra: docs Requires-Dist: sphinx; extra == "docs" Flask-SocketIO ============== [![Build status](https://github.com/miguelgrinberg/flask-socketio/workflows/build/badge.svg)](https://github.com/miguelgrinberg/Flask-SocketIO/actions) [![codecov](https://codecov.io/gh/miguelgrinberg/flask-socketio/branch/main/graph/badge.svg)](https://codecov.io/gh/miguelgrinberg/flask-socketio) Socket.IO integration for Flask applications. Sponsors -------- The following organizations are funding this project: ![Socket.IO](https://images.opencollective.com/socketio/050e5eb/logo/64.png)
[Socket.IO](https://socket.io) | [Add your company here!](https://github.com/sponsors/miguelgrinberg)| -|- Many individual sponsors also support this project through small ongoing contributions. Why not [join them](https://github.com/sponsors/miguelgrinberg)? Installation ------------ You can install this package as usual with pip: pip install flask-socketio Example ------- ```py from flask import Flask, render_template from flask_socketio import SocketIO, emit app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app) @app.route('/') def index(): return render_template('index.html') @socketio.event def my_event(message): emit('my response', {'data': 'got it!'}) if __name__ == '__main__': socketio.run(app) ``` Resources --------- - [Tutorial](http://blog.miguelgrinberg.com/post/easy-websockets-with-flask-and-gevent) - [Documentation](http://flask-socketio.readthedocs.io/en/latest/) - [PyPI](https://pypi.python.org/pypi/Flask-SocketIO) - [Change Log](https://github.com/miguelgrinberg/Flask-SocketIO/blob/main/CHANGES.md) - Questions? See the [questions](https://stackoverflow.com/questions/tagged/flask-socketio) others have asked on Stack Overflow, or [ask](https://stackoverflow.com/questions/ask?tags=python+flask-socketio+python-socketio) your own question. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1736192976.0 flask_socketio-5.5.1/src/Flask_SocketIO.egg-info/SOURCES.txt0000775000175000017500000000120114737031720023060 0ustar00miguelmiguelLICENSE MANIFEST.in README.md pyproject.toml test_socketio.py tox.ini docs/Makefile docs/api.rst docs/conf.py docs/deployment.rst docs/getting_started.rst docs/implementation_notes.rst docs/index.rst docs/intro.rst docs/make.bat docs/upgrading.rst docs/_static/README.md docs/_static/custom.css src/Flask_SocketIO.egg-info/PKG-INFO src/Flask_SocketIO.egg-info/SOURCES.txt src/Flask_SocketIO.egg-info/dependency_links.txt src/Flask_SocketIO.egg-info/not-zip-safe src/Flask_SocketIO.egg-info/requires.txt src/Flask_SocketIO.egg-info/top_level.txt src/flask_socketio/__init__.py src/flask_socketio/namespace.py src/flask_socketio/test_client.py././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1736192976.0 flask_socketio-5.5.1/src/Flask_SocketIO.egg-info/dependency_links.txt0000775000175000017500000000000114737031720025250 0ustar00miguelmiguel ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1686651103.0 flask_socketio-5.5.1/src/Flask_SocketIO.egg-info/not-zip-safe0000775000175000017500000000000114442040337023425 0ustar00miguelmiguel ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1736192976.0 flask_socketio-5.5.1/src/Flask_SocketIO.egg-info/requires.txt0000775000175000017500000000006214737031720023600 0ustar00miguelmiguelFlask>=0.9 python-socketio>=5.12.0 [docs] sphinx ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1736192976.0 flask_socketio-5.5.1/src/Flask_SocketIO.egg-info/top_level.txt0000775000175000017500000000001714737031720023732 0ustar00miguelmiguelflask_socketio ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1736192976.7210176 flask_socketio-5.5.1/src/flask_socketio/0000775000175000017500000000000014737031721017706 5ustar00miguelmiguel././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734545045.0 flask_socketio-5.5.1/src/flask_socketio/__init__.py0000664000175000017500000015317014730607225022027 0ustar00miguelmiguelfrom functools import wraps import os import sys # make sure gevent-socketio is not installed, as it conflicts with # python-socketio gevent_socketio_found = True try: from socketio import socketio_manage # noqa: F401 except ImportError: gevent_socketio_found = False if gevent_socketio_found: print('The gevent-socketio package is incompatible with this version of ' 'the Flask-SocketIO extension. Please uninstall it, and then ' 'install the latest version of python-socketio in its place.') sys.exit(1) import flask from flask import has_request_context, json as flask_json from flask.sessions import SessionMixin import socketio from socketio.exceptions import ConnectionRefusedError # noqa: F401 from werkzeug.debug import DebuggedApplication from werkzeug._reloader import run_with_reloader from .namespace import Namespace from .test_client import SocketIOTestClient class _SocketIOMiddleware(socketio.WSGIApp): """This WSGI middleware simply exposes the Flask application in the WSGI environment before executing the request. """ def __init__(self, socketio_app, flask_app, socketio_path='socket.io'): self.flask_app = flask_app super().__init__(socketio_app, flask_app.wsgi_app, socketio_path=socketio_path) def __call__(self, environ, start_response): environ = environ.copy() environ['flask.app'] = self.flask_app return super().__call__(environ, start_response) class _ManagedSession(dict, SessionMixin): """This class is used for user sessions that are managed by Flask-SocketIO. It is simple dict, expanded with the Flask session attributes.""" pass class SocketIO: """Create a Flask-SocketIO server. :param app: The flask application instance. If the application instance isn't known at the time this class is instantiated, then call ``socketio.init_app(app)`` once the application instance is available. :param manage_session: If set to ``True``, this extension manages the user session for Socket.IO events. If set to ``False``, Flask's own session management is used. When using Flask's cookie based sessions it is recommended that you leave this set to the default of ``True``. When using server-side sessions, a ``False`` setting enables sharing the user session between HTTP routes and Socket.IO events. :param message_queue: A connection URL for a message queue service the server can use for multi-process communication. A message queue is not required when using a single server process. :param channel: The channel name, when using a message queue. If a channel isn't specified, a default channel will be used. If multiple clusters of SocketIO processes need to use the same message queue without interfering with each other, then each cluster should use a different channel. :param path: The path where the Socket.IO server is exposed. Defaults to ``'socket.io'``. Leave this as is unless you know what you are doing. :param resource: Alias to ``path``. :param kwargs: Socket.IO and Engine.IO server options. The Socket.IO server options are detailed below: :param client_manager: The client manager instance that will manage the client list. When this is omitted, the client list is stored in an in-memory structure, so the use of multiple connected servers is not possible. In most cases, this argument does not need to be set explicitly. :param logger: To enable logging set to ``True`` or pass a logger object to use. To disable logging set to ``False``. The default is ``False``. Note that fatal errors will be logged even when ``logger`` is ``False``. :param json: An alternative json module to use for encoding and decoding packets. Custom json modules must have ``dumps`` and ``loads`` functions that are compatible with the standard library versions. To use the same json encoder and decoder as a Flask application, use ``flask.json``. :param async_handlers: If set to ``True``, event handlers for a client are executed in separate threads. To run handlers for a client synchronously, set to ``False``. The default is ``True``. :param always_connect: When set to ``False``, new connections are provisory until the connect handler returns something other than ``False``, at which point they are accepted. When set to ``True``, connections are immediately accepted, and then if the connect handler returns ``False`` a disconnect is issued. Set to ``True`` if you need to emit events from the connect handler and your client is confused when it receives events before the connection acceptance. In any other case use the default of ``False``. The Engine.IO server configuration supports the following settings: :param async_mode: The asynchronous model to use. See the Deployment section in the documentation for a description of the available options. Valid async modes are ``threading``, ``eventlet``, ``gevent`` and ``gevent_uwsgi``. If this argument is not given, ``eventlet`` is tried first, then ``gevent_uwsgi``, then ``gevent``, and finally ``threading``. The first async mode that has all its dependencies installed is then one that is chosen. :param ping_interval: The interval in seconds at which the server pings the client. The default is 25 seconds. For advanced control, a two element tuple can be given, where the first number is the ping interval and the second is a grace period added by the server. :param ping_timeout: The time in seconds that the client waits for the server to respond before disconnecting. The default is 5 seconds. :param max_http_buffer_size: The maximum size of a message when using the polling transport. The default is 1,000,000 bytes. :param allow_upgrades: Whether to allow transport upgrades or not. The default is ``True``. :param http_compression: Whether to compress packages when using the polling transport. The default is ``True``. :param compression_threshold: Only compress messages when their byte size is greater than this value. The default is 1024 bytes. :param cookie: If set to a string, it is the name of the HTTP cookie the server sends back to the client containing the client session id. If set to a dictionary, the ``'name'`` key contains the cookie name and other keys define cookie attributes, where the value of each attribute can be a string, a callable with no arguments, or a boolean. If set to ``None`` (the default), a cookie is not sent to the client. :param cors_allowed_origins: Origin or list of origins that are allowed to connect to this server. Only the same origin is allowed by default. Set this argument to ``'*'`` to allow all origins, or to ``[]`` to disable CORS handling. :param cors_credentials: Whether credentials (cookies, authentication) are allowed in requests to this server. The default is ``True``. :param monitor_clients: If set to ``True``, a background task will ensure inactive clients are closed. Set to ``False`` to disable the monitoring task (not recommended). The default is ``True``. :param engineio_logger: To enable Engine.IO logging set to ``True`` or pass a logger object to use. To disable logging set to ``False``. The default is ``False``. Note that fatal errors are logged even when ``engineio_logger`` is ``False``. """ reason = socketio.Server.reason def __init__(self, app=None, **kwargs): self.server = None self.server_options = {} self.wsgi_server = None self.handlers = [] self.namespace_handlers = [] self.exception_handlers = {} self.default_exception_handler = None self.manage_session = True # We can call init_app when: # - we were given the Flask app instance (standard initialization) # - we were not given the app, but we were given a message_queue # (standard initialization for auxiliary process) # In all other cases we collect the arguments and assume the client # will call init_app from an app factory function. if app is not None or 'message_queue' in kwargs: self.init_app(app, **kwargs) else: self.server_options.update(kwargs) def init_app(self, app, **kwargs): if app is not None: if not hasattr(app, 'extensions'): app.extensions = {} # pragma: no cover app.extensions['socketio'] = self self.server_options.update(kwargs) self.manage_session = self.server_options.pop('manage_session', self.manage_session) if 'client_manager' not in kwargs: url = self.server_options.get('message_queue', None) channel = self.server_options.pop('channel', 'flask-socketio') write_only = app is None if url: if url.startswith(('redis://', "rediss://")): queue_class = socketio.RedisManager elif url.startswith('kafka://'): queue_class = socketio.KafkaManager elif url.startswith('zmq'): queue_class = socketio.ZmqManager else: queue_class = socketio.KombuManager queue = queue_class(url, channel=channel, write_only=write_only) self.server_options['client_manager'] = queue if 'json' in self.server_options and \ self.server_options['json'] == flask_json: # flask's json module is tricky to use because its output # changes when it is invoked inside or outside the app context # so here to prevent any ambiguities we replace it with wrappers # that ensure that the app context is always present class FlaskSafeJSON: @staticmethod def dumps(*args, **kwargs): with app.app_context(): return flask_json.dumps(*args, **kwargs) @staticmethod def loads(*args, **kwargs): with app.app_context(): return flask_json.loads(*args, **kwargs) self.server_options['json'] = FlaskSafeJSON resource = self.server_options.pop('path', None) or \ self.server_options.pop('resource', None) or 'socket.io' if resource.startswith('/'): resource = resource[1:] if os.environ.get('FLASK_RUN_FROM_CLI'): if self.server_options.get('async_mode') is None: self.server_options['async_mode'] = 'threading' self.server = socketio.Server(**self.server_options) self.async_mode = self.server.async_mode for handler in self.handlers: self.server.on(handler[0], handler[1], namespace=handler[2]) for namespace_handler in self.namespace_handlers: self.server.register_namespace(namespace_handler) if app is not None: # here we attach the SocketIO middleware to the SocketIO object so # it can be referenced later if debug middleware needs to be # inserted self.sockio_mw = _SocketIOMiddleware(self.server, app, socketio_path=resource) app.wsgi_app = self.sockio_mw def on(self, message, namespace=None): """Decorator to register a SocketIO event handler. This decorator must be applied to SocketIO event handlers. Example:: @socketio.on('my event', namespace='/chat') def handle_my_custom_event(json): print('received json: ' + str(json)) :param message: The name of the event. This is normally a user defined string, but a few event names are already defined. Use ``'message'`` to define a handler that takes a string payload, ``'json'`` to define a handler that takes a JSON blob payload, ``'connect'`` or ``'disconnect'`` to create handlers for connection and disconnection events. :param namespace: The namespace on which the handler is to be registered. Defaults to the global namespace. """ namespace = namespace or '/' def decorator(handler): @wraps(handler) def _handler(sid, *args): nonlocal namespace real_ns = namespace if namespace == '*': real_ns = sid sid = args[0] args = args[1:] real_msg = message if message == '*': real_msg = sid sid = args[0] args = [real_msg] + list(args[1:]) return self._handle_event(handler, message, real_ns, sid, *args) if self.server: self.server.on(message, _handler, namespace=namespace) else: self.handlers.append((message, _handler, namespace)) return handler return decorator def on_error(self, namespace=None): """Decorator to define a custom error handler for SocketIO events. This decorator can be applied to a function that acts as an error handler for a namespace. This handler will be invoked when a SocketIO event handler raises an exception. The handler function must accept one argument, which is the exception raised. Example:: @socketio.on_error(namespace='/chat') def chat_error_handler(e): print('An error has occurred: ' + str(e)) :param namespace: The namespace for which to register the error handler. Defaults to the global namespace. """ namespace = namespace or '/' def decorator(exception_handler): if not callable(exception_handler): raise ValueError('exception_handler must be callable') self.exception_handlers[namespace] = exception_handler return exception_handler return decorator def on_error_default(self, exception_handler): """Decorator to define a default error handler for SocketIO events. This decorator can be applied to a function that acts as a default error handler for any namespaces that do not have a specific handler. Example:: @socketio.on_error_default def error_handler(e): print('An error has occurred: ' + str(e)) """ if not callable(exception_handler): raise ValueError('exception_handler must be callable') self.default_exception_handler = exception_handler return exception_handler def on_event(self, message, handler, namespace=None): """Register a SocketIO event handler. ``on_event`` is the non-decorator version of ``'on'``. Example:: def on_foo_event(json): print('received json: ' + str(json)) socketio.on_event('my event', on_foo_event, namespace='/chat') :param message: The name of the event. This is normally a user defined string, but a few event names are already defined. Use ``'message'`` to define a handler that takes a string payload, ``'json'`` to define a handler that takes a JSON blob payload, ``'connect'`` or ``'disconnect'`` to create handlers for connection and disconnection events. :param handler: The function that handles the event. :param namespace: The namespace on which the handler is to be registered. Defaults to the global namespace. """ self.on(message, namespace=namespace)(handler) def event(self, *args, **kwargs): """Decorator to register an event handler. This is a simplified version of the ``on()`` method that takes the event name from the decorated function. Example usage:: @socketio.event def my_event(data): print('Received data: ', data) The above example is equivalent to:: @socketio.on('my_event') def my_event(data): print('Received data: ', data) A custom namespace can be given as an argument to the decorator:: @socketio.event(namespace='/test') def my_event(data): print('Received data: ', data) """ if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): # the decorator was invoked without arguments # args[0] is the decorated function return self.on(args[0].__name__)(args[0]) else: # the decorator was invoked with arguments def set_handler(handler): return self.on(handler.__name__, *args, **kwargs)(handler) return set_handler def on_namespace(self, namespace_handler): if not isinstance(namespace_handler, Namespace): raise ValueError('Not a namespace instance.') namespace_handler._set_socketio(self) if self.server: self.server.register_namespace(namespace_handler) else: self.namespace_handlers.append(namespace_handler) def emit(self, event, *args, **kwargs): """Emit a server generated SocketIO event. This function emits a SocketIO event to one or more connected clients. A JSON blob can be attached to the event as payload. This function can be used outside of a SocketIO event context, so it is appropriate to use when the server is the originator of an event, outside of any client context, such as in a regular HTTP request handler or a background task. Example:: @app.route('/ping') def ping(): socketio.emit('ping event', {'data': 42}, namespace='/chat') :param event: The name of the user event to emit. :param args: A dictionary with the JSON data to send as payload. :param namespace: The namespace under which the message is to be sent. Defaults to the global namespace. :param to: Send the message to all the users in the given room, or to the user with the given session ID. If this parameter is not included, the event is sent to all connected users. :param include_self: ``True`` to include the sender when broadcasting or addressing a room, or ``False`` to send to everyone but the sender. :param skip_sid: The session id of a client to ignore when broadcasting or addressing a room. This is typically set to the originator of the message, so that everyone except that client receive the message. To skip multiple sids pass a list. :param callback: If given, this function will be called to acknowledge that the client has received the message. The arguments that will be passed to the function are those provided by the client. Callback functions can only be used when addressing an individual client. """ namespace = kwargs.pop('namespace', '/') to = kwargs.pop('to', None) or kwargs.pop('room', None) include_self = kwargs.pop('include_self', True) skip_sid = kwargs.pop('skip_sid', None) if not include_self and not skip_sid: skip_sid = flask.request.sid callback = kwargs.pop('callback', None) if callback: # wrap the callback so that it sets app app and request contexts sid = None original_callback = callback original_namespace = namespace if has_request_context(): sid = getattr(flask.request, 'sid', None) original_namespace = getattr(flask.request, 'namespace', None) def _callback_wrapper(*args): return self._handle_event(original_callback, None, original_namespace, sid, *args) if sid: # the callback wrapper above will install a request context # before invoking the original callback # we only use it if the emit was issued from a Socket.IO # populated request context (i.e. request.sid is defined) callback = _callback_wrapper self.server.emit(event, *args, namespace=namespace, to=to, skip_sid=skip_sid, callback=callback, **kwargs) def call(self, event, *args, **kwargs): # pragma: no cover """Emit a SocketIO event and wait for the response. This method issues an emit with a callback and waits for the callback to be invoked by the client before returning. If the callback isn’t invoked before the timeout, then a TimeoutError exception is raised. If the Socket.IO connection drops during the wait, this method still waits until the specified timeout. Example:: def get_status(client, data): status = call('status', {'data': data}, to=client) :param event: The name of the user event to emit. :param args: A dictionary with the JSON data to send as payload. :param namespace: The namespace under which the message is to be sent. Defaults to the global namespace. :param to: The session ID of the recipient client. :param timeout: The waiting timeout. If the timeout is reached before the client acknowledges the event, then a ``TimeoutError`` exception is raised. The default is 60 seconds. :param ignore_queue: Only used when a message queue is configured. If set to ``True``, the event is emitted to the client directly, without going through the queue. This is more efficient, but only works when a single server process is used, or when there is a single addressee. It is recommended to always leave this parameter with its default value of ``False``. """ namespace = kwargs.pop('namespace', '/') to = kwargs.pop('to', None) or kwargs.pop('room', None) return self.server.call(event, *args, namespace=namespace, to=to, **kwargs) def send(self, data, json=False, namespace=None, to=None, callback=None, include_self=True, skip_sid=None, **kwargs): """Send a server-generated SocketIO message. This function sends a simple SocketIO message to one or more connected clients. The message can be a string or a JSON blob. This is a simpler version of ``emit()``, which should be preferred. This function can be used outside of a SocketIO event context, so it is appropriate to use when the server is the originator of an event. :param data: The message to send, either a string or a JSON blob. :param json: ``True`` if ``message`` is a JSON blob, ``False`` otherwise. :param namespace: The namespace under which the message is to be sent. Defaults to the global namespace. :param to: Send the message to all the users in the given room, or to the user with the given session ID. If this parameter is not included, the event is sent to all connected users. :param include_self: ``True`` to include the sender when broadcasting or addressing a room, or ``False`` to send to everyone but the sender. :param skip_sid: The session id of a client to ignore when broadcasting or addressing a room. This is typically set to the originator of the message, so that everyone except that client receive the message. To skip multiple sids pass a list. :param callback: If given, this function will be called to acknowledge that the client has received the message. The arguments that will be passed to the function are those provided by the client. Callback functions can only be used when addressing an individual client. """ skip_sid = flask.request.sid if not include_self else skip_sid if json: self.emit('json', data, namespace=namespace, to=to, skip_sid=skip_sid, callback=callback, **kwargs) else: self.emit('message', data, namespace=namespace, to=to, skip_sid=skip_sid, callback=callback, **kwargs) def close_room(self, room, namespace=None): """Close a room. This function removes any users that are in the given room and then deletes the room from the server. This function can be used outside of a SocketIO event context. :param room: The name of the room to close. :param namespace: The namespace under which the room exists. Defaults to the global namespace. """ self.server.close_room(room, namespace) def run(self, app, host=None, port=None, **kwargs): # pragma: no cover """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 reloader_options: A dictionary with options that are passed to the Flask reloader, such as ``extra_files``, ``reloader_type``, etc. :param extra_files: A list of additional files that the Flask reloader should watch. Defaults to ``None``. Deprecated, use ``reloader_options`` instead. :param log_output: If ``True``, the server logs all incoming 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 allow_unsafe_werkzeug: Set to ``True`` to allow the use of the Werkzeug web server in a production setting. Default is ``False``. Set to ``True`` at your own risk. :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) reloader_options = kwargs.pop('reloader_options', {}) if extra_files: reloader_options['extra_files'] = extra_files 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) allow_unsafe_werkzeug = kwargs.pop('allow_unsafe_werkzeug', False) if self.server.eio.async_mode == 'threading': try: import simple_websocket # noqa: F401 except ImportError: from werkzeug._internal import _log _log('warning', 'WebSocket transport not available. Install ' 'simple-websocket for improved performance.') if not sys.stdin or not sys.stdin.isatty(): # pragma: no cover if not allow_unsafe_werkzeug: raise RuntimeError('The Werkzeug web server is not ' 'designed to run in production. Pass ' 'allow_unsafe_werkzeug=True to the ' 'run() method to disable this error.') else: from werkzeug._internal import _log _log('warning', ('Werkzeug appears to be used in a ' 'production deployment. Consider ' 'switching to a production web server ' 'instead.')) app.run(host=host, port=port, threaded=True, use_reloader=use_reloader, **reloader_options, **kwargs) elif self.server.eio.async_mode == 'eventlet': def run_server(): import eventlet import eventlet.wsgi import eventlet.green addresses = eventlet.green.socket.getaddrinfo(host, port) if not addresses: raise RuntimeError( 'Could not resolve host to a valid address') eventlet_socket = eventlet.listen(addresses[0][4], addresses[0][0]) # 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 and kwargs[k] is not None} for k in ssl_args: kwargs.pop(k, None) if len(ssl_params) > 0: 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, **reloader_options) else: run_server() elif self.server.eio.async_mode == 'gevent': from gevent import pywsgi try: from geventwebsocket.handler import WebSocketHandler gevent_websocket = True except ImportError: # WebSocket support will come from the simple-websocket package gevent_websocket = False log = 'default' if not log_output: log = None if gevent_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, **kwargs) if use_reloader: # monkey patching is required by the reloader from gevent import monkey monkey.patch_thread() monkey.patch_time() def run_server(): self.wsgi_server.serve_forever() run_with_reloader(run_server, **reloader_options) else: self.wsgi_server.serve_forever() def stop(self): """Stop a running SocketIO web server. This method must be called from a HTTP or SocketIO handler function. """ if self.server.eio.async_mode == 'threading': func = flask.request.environ.get('werkzeug.server.shutdown') if func: func() else: raise RuntimeError('Cannot stop unknown web server') elif self.server.eio.async_mode == 'eventlet': raise SystemExit elif self.server.eio.async_mode == 'gevent': self.wsgi_server.stop() def start_background_task(self, target, *args, **kwargs): """Start a background task using the appropriate async model. This is a utility function that applications can use to start a background task using the method that is compatible with the selected async mode. :param target: the target function to execute. :param args: arguments to pass to the function. :param kwargs: keyword arguments to pass to the function. This function returns an object that represents the background task, on which the ``join()`` method can be invoked to wait for the task to complete. """ return self.server.start_background_task(target, *args, **kwargs) def sleep(self, seconds=0): """Sleep for the requested amount of time using the appropriate async model. This is a utility function that applications can use to put a task to sleep without having to worry about using the correct call for the selected async mode. """ return self.server.sleep(seconds) def test_client(self, app, namespace=None, query_string=None, headers=None, auth=None, flask_test_client=None): """The Socket.IO test client is useful for testing a Flask-SocketIO server. It works in a similar way to the Flask Test Client, but adapted to the Socket.IO server. :param app: The Flask application instance. :param namespace: The namespace for the client. If not provided, the client connects to the server on the global namespace. :param query_string: A string with custom query string arguments. :param headers: A dictionary with custom HTTP headers. :param auth: Optional authentication data, given as a dictionary. :param flask_test_client: The instance of the Flask test client currently in use. Passing the Flask test client is optional, but is necessary if you want the Flask user session and any other cookies set in HTTP routes accessible from Socket.IO events. """ return SocketIOTestClient(app, self, namespace=namespace, query_string=query_string, headers=headers, auth=auth, flask_test_client=flask_test_client) def _handle_event(self, handler, message, namespace, sid, *args): environ = self.server.get_environ(sid, namespace=namespace) if not environ: # we don't have record of this client, ignore this event return '', 400 app = environ['flask.app'] with app.request_context(environ): if self.manage_session: # manage a separate session for this client's Socket.IO events # created as a copy of the regular user session if 'saved_session' not in environ: environ['saved_session'] = _ManagedSession(flask.session) session_obj = environ['saved_session'] if hasattr(flask, 'globals') and \ hasattr(flask.globals, 'request_ctx'): # update session for Flask >= 2.2 ctx = flask.globals.request_ctx._get_current_object() else: # pragma: no cover # update session for Flask < 2.2 ctx = flask._request_ctx_stack.top ctx.session = session_obj else: # let Flask handle the user session # for cookie based sessions, this effectively freezes the # session to its state at connection time # for server-side sessions, this allows HTTP and Socket.IO to # share the session, with both having read/write access to it session_obj = flask.session._get_current_object() flask.request.sid = sid flask.request.namespace = namespace flask.request.event = {'message': message, 'args': args} try: if message == 'connect': auth = args[1] if len(args) > 1 else None try: ret = handler(auth) except TypeError: ret = handler() else: ret = handler(*args) except ConnectionRefusedError: raise # let this error bubble up to python-socketio except: err_handler = self.exception_handlers.get( namespace, self.default_exception_handler) if err_handler is None: raise type, value, traceback = sys.exc_info() return err_handler(value) if not self.manage_session: # when Flask is managing the user session, it needs to save it if not hasattr(session_obj, 'modified') or \ session_obj.modified: resp = app.response_class() app.session_interface.save_session(app, session_obj, resp) return ret def emit(event, *args, **kwargs): """Emit a SocketIO event. This function emits a SocketIO event to one or more connected clients. A JSON blob can be attached to the event as payload. This is a function that can only be called from a SocketIO event handler, as in obtains some information from the current client context. Example:: @socketio.on('my event') def handle_my_custom_event(json): emit('my response', {'data': 42}) :param event: The name of the user event to emit. :param args: A dictionary with the JSON data to send as payload. :param namespace: The namespace under which the message is to be sent. Defaults to the namespace used by the originating event. A ``'/'`` can be used to explicitly specify the global namespace. :param callback: Callback function to invoke with the client's acknowledgement. :param broadcast: ``True`` to send the message to all clients, or ``False`` to only reply to the sender of the originating event. :param to: Send the message to all the users in the given room, or to the user with the given session ID. If this argument is not set and ``broadcast`` is ``False``, then the message is sent only to the originating user. :param include_self: ``True`` to include the sender when broadcasting or addressing a room, or ``False`` to send to everyone but the sender. :param skip_sid: The session id of a client to ignore when broadcasting or addressing a room. This is typically set to the originator of the message, so that everyone except that client receive the message. To skip multiple sids pass a list. :param ignore_queue: Only used when a message queue is configured. If set to ``True``, the event is emitted to the clients directly, without going through the queue. This is more efficient, but only works when a single server process is used, or when there is a single addressee. It is recommended to always leave this parameter with its default value of ``False``. """ if 'namespace' in kwargs: namespace = kwargs['namespace'] else: namespace = flask.request.namespace callback = kwargs.get('callback') broadcast = kwargs.get('broadcast') to = kwargs.pop('to', None) or kwargs.pop('room', None) if to is None and not broadcast: to = flask.request.sid include_self = kwargs.get('include_self', True) skip_sid = kwargs.get('skip_sid') ignore_queue = kwargs.get('ignore_queue', False) socketio = flask.current_app.extensions['socketio'] return socketio.emit(event, *args, namespace=namespace, to=to, include_self=include_self, skip_sid=skip_sid, callback=callback, ignore_queue=ignore_queue) def call(event, *args, **kwargs): # pragma: no cover """Emit a SocketIO event and wait for the response. This function issues an emit with a callback and waits for the callback to be invoked by the client before returning. If the callback isn’t invoked before the timeout, then a TimeoutError exception is raised. If the Socket.IO connection drops during the wait, this method still waits until the specified timeout. Example:: def get_status(client, data): status = call('status', {'data': data}, to=client) :param event: The name of the user event to emit. :param args: A dictionary with the JSON data to send as payload. :param namespace: The namespace under which the message is to be sent. Defaults to the namespace used by the originating event. A ``'/'`` can be used to explicitly specify the global namespace. :param to: The session ID of the recipient client. If this argument is not given, the event is sent to the originating client. :param timeout: The waiting timeout. If the timeout is reached before the client acknowledges the event, then a ``TimeoutError`` exception is raised. The default is 60 seconds. :param ignore_queue: Only used when a message queue is configured. If set to ``True``, the event is emitted to the client directly, without going through the queue. This is more efficient, but only works when a single server process is used, or when there is a single addressee. It is recommended to always leave this parameter with its default value of ``False``. """ if 'namespace' in kwargs: namespace = kwargs['namespace'] else: namespace = flask.request.namespace to = kwargs.pop('to', None) or kwargs.pop('room', None) if to is None: to = flask.request.sid timeout = kwargs.get('timeout', 60) ignore_queue = kwargs.get('ignore_queue', False) socketio = flask.current_app.extensions['socketio'] return socketio.call(event, *args, namespace=namespace, to=to, ignore_queue=ignore_queue, timeout=timeout) def send(message, **kwargs): """Send a SocketIO message. This function sends a simple SocketIO message to one or more connected clients. The message can be a string or a JSON blob. This is a simpler version of ``emit()``, which should be preferred. This is a function that can only be called from a SocketIO event handler. :param message: The message to send, either a string or a JSON blob. :param json: ``True`` if ``message`` is a JSON blob, ``False`` otherwise. :param namespace: The namespace under which the message is to be sent. Defaults to the namespace used by the originating event. An empty string can be used to use the global namespace. :param callback: Callback function to invoke with the client's acknowledgement. :param broadcast: ``True`` to send the message to all connected clients, or ``False`` to only reply to the sender of the originating event. :param to: Send the message to all the users in the given room, or to the user with the given session ID. If this argument is not set and ``broadcast`` is ``False``, then the message is sent only to the originating user. :param include_self: ``True`` to include the sender when broadcasting or addressing a room, or ``False`` to send to everyone but the sender. :param skip_sid: The session id of a client to ignore when broadcasting or addressing a room. This is typically set to the originator of the message, so that everyone except that client receive the message. To skip multiple sids pass a list. :param ignore_queue: Only used when a message queue is configured. If set to ``True``, the event is emitted to the clients directly, without going through the queue. This is more efficient, but only works when a single server process is used, or when there is a single addressee. It is recommended to always leave this parameter with its default value of ``False``. """ json = kwargs.get('json', False) if 'namespace' in kwargs: namespace = kwargs['namespace'] else: namespace = flask.request.namespace callback = kwargs.get('callback') broadcast = kwargs.get('broadcast') to = kwargs.pop('to', None) or kwargs.pop('room', None) if to is None and not broadcast: to = flask.request.sid include_self = kwargs.get('include_self', True) skip_sid = kwargs.get('skip_sid') ignore_queue = kwargs.get('ignore_queue', False) socketio = flask.current_app.extensions['socketio'] return socketio.send(message, json=json, namespace=namespace, to=to, include_self=include_self, skip_sid=skip_sid, callback=callback, ignore_queue=ignore_queue) def join_room(room, sid=None, namespace=None): """Join a room. This function puts the user in a room, under the current namespace. The user and the namespace are obtained from the event context. This is a function that can only be called from a SocketIO event handler. Example:: @socketio.on('join') def on_join(data): username = session['username'] room = data['room'] join_room(room) send(username + ' has entered the room.', to=room) :param room: The name of the room to join. :param sid: The session id of the client. If not provided, the client is obtained from the request context. :param namespace: The namespace for the room. If not provided, the namespace is obtained from the request context. """ socketio = flask.current_app.extensions['socketio'] sid = sid or flask.request.sid namespace = namespace or flask.request.namespace socketio.server.enter_room(sid, room, namespace=namespace) def leave_room(room, sid=None, namespace=None): """Leave a room. This function removes the user from a room, under the current namespace. The user and the namespace are obtained from the event context. Example:: @socketio.on('leave') def on_leave(data): username = session['username'] room = data['room'] leave_room(room) send(username + ' has left the room.', to=room) :param room: The name of the room to leave. :param sid: The session id of the client. If not provided, the client is obtained from the request context. :param namespace: The namespace for the room. If not provided, the namespace is obtained from the request context. """ socketio = flask.current_app.extensions['socketio'] sid = sid or flask.request.sid namespace = namespace or flask.request.namespace socketio.server.leave_room(sid, room, namespace=namespace) def close_room(room, namespace=None): """Close a room. This function removes any users that are in the given room and then deletes the room from the server. :param room: The name of the room to close. :param namespace: The namespace for the room. If not provided, the namespace is obtained from the request context. """ socketio = flask.current_app.extensions['socketio'] namespace = namespace or flask.request.namespace socketio.server.close_room(room, namespace=namespace) def rooms(sid=None, namespace=None): """Return a list of the rooms the client is in. This function returns all the rooms the client has entered, including its own room, assigned by the Socket.IO server. :param sid: The session id of the client. If not provided, the client is obtained from the request context. :param namespace: The namespace for the room. If not provided, the namespace is obtained from the request context. """ socketio = flask.current_app.extensions['socketio'] sid = sid or flask.request.sid namespace = namespace or flask.request.namespace return socketio.server.rooms(sid, namespace=namespace) def disconnect(sid=None, namespace=None, silent=False): """Disconnect the client. This function terminates the connection with the client. As a result of this call the client will receive a disconnect event. Example:: @socketio.on('message') def receive_message(msg): if is_banned(session['username']): disconnect() else: # ... :param sid: The session id of the client. If not provided, the client is obtained from the request context. :param namespace: The namespace for the room. If not provided, the namespace is obtained from the request context. :param silent: this option is deprecated. """ socketio = flask.current_app.extensions['socketio'] sid = sid or flask.request.sid namespace = namespace or flask.request.namespace return socketio.server.disconnect(sid, namespace=namespace) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734544941.0 flask_socketio-5.5.1/src/flask_socketio/namespace.py0000664000175000017500000000443114730607055022220 0ustar00miguelmiguelfrom socketio import Namespace as _Namespace class Namespace(_Namespace): def __init__(self, namespace=None): super().__init__(namespace) self.socketio = None def _set_socketio(self, socketio): self.socketio = socketio def trigger_event(self, event, *args): """Dispatch an event to the proper handler method. In the most common usage, this method is not overloaded by subclasses, as it performs the routing of events to methods. However, this method can be overridden if special dispatching rules are needed, or if having a single method that catches all events is desired. """ handler_name = 'on_' + (event or '') if not hasattr(self, handler_name): # there is no handler for this event, so we ignore it return handler = getattr(self, handler_name) try: return self.socketio._handle_event(handler, event, self.namespace, *args) except TypeError: if event == 'disconnect': # legacy disconnect events do not have the reason argument return self.socketio._handle_event( handler, event, self.namespace, *args[:-1]) else: raise def emit(self, event, data=None, room=None, include_self=True, namespace=None, callback=None): """Emit a custom event to one or more connected clients.""" return self.socketio.emit(event, data, room=room, include_self=include_self, namespace=namespace or self.namespace, callback=callback) def send(self, data, room=None, include_self=True, namespace=None, callback=None): """Send a message to one or more connected clients.""" return self.socketio.send(data, room=room, include_self=include_self, namespace=namespace or self.namespace, callback=callback) def close_room(self, room, namespace=None): """Close a room.""" return self.socketio.close_room(room=room, namespace=namespace or self.namespace) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734028986.0 flask_socketio-5.5.1/src/flask_socketio/test_client.py0000664000175000017500000002542214726627272022614 0ustar00miguelmiguelimport uuid from socketio import packet from socketio.pubsub_manager import PubSubManager from werkzeug.test import EnvironBuilder class SocketIOTestClient: """ This class is useful for testing a Flask-SocketIO server. It works in a similar way to the Flask Test Client, but adapted to the Socket.IO server. :param app: The Flask application instance. :param socketio: The application's ``SocketIO`` instance. :param namespace: The namespace for the client. If not provided, the client connects to the server on the global namespace. :param query_string: A string with custom query string arguments. :param headers: A dictionary with custom HTTP headers. :param auth: Optional authentication data, given as a dictionary. :param flask_test_client: The instance of the Flask test client currently in use. Passing the Flask test client is optional, but is necessary if you want the Flask user session and any other cookies set in HTTP routes accessible from Socket.IO events. """ clients = {} def __init__(self, app, socketio, namespace=None, query_string=None, headers=None, auth=None, flask_test_client=None): def _mock_send_packet(eio_sid, pkt): # make sure the packet can be encoded and decoded epkt = pkt.encode() if not isinstance(epkt, list): pkt = packet.Packet(encoded_packet=epkt) else: pkt = packet.Packet(encoded_packet=epkt[0]) for att in epkt[1:]: pkt.add_attachment(att) client = self.clients.get(eio_sid) if not client: return if pkt.packet_type == packet.EVENT or \ pkt.packet_type == packet.BINARY_EVENT: if pkt.data[0] == 'message' or pkt.data[0] == 'json': client.queue.append({ 'name': pkt.data[0], 'args': pkt.data[1], 'namespace': pkt.namespace or '/'}) else: client.queue.append({ 'name': pkt.data[0], 'args': pkt.data[1:], 'namespace': pkt.namespace or '/'}) elif pkt.packet_type == packet.ACK or \ pkt.packet_type == packet.BINARY_ACK: client.acks = {'args': pkt.data, 'namespace': pkt.namespace or '/'} elif pkt.packet_type in [packet.DISCONNECT, packet.CONNECT_ERROR]: client.connected[pkt.namespace or '/'] = False _current_packet = None def _mock_send_eio_packet(eio_sid, eio_pkt): nonlocal _current_packet if _current_packet is not None: _current_packet.add_attachment(eio_pkt.data) if _current_packet.attachment_count == \ len(_current_packet.attachments): _mock_send_packet(eio_sid, _current_packet) _current_packet = None else: pkt = packet.Packet(encoded_packet=eio_pkt.data) if pkt.attachment_count == 0: _mock_send_packet(eio_sid, pkt) else: _current_packet = pkt self.app = app self.flask_test_client = flask_test_client self.eio_sid = uuid.uuid4().hex self.clients[self.eio_sid] = self self.callback_counter = 0 self.socketio = socketio self.connected = {} self.queue = [] self.acks = None socketio.server._send_packet = _mock_send_packet socketio.server._send_eio_packet = _mock_send_eio_packet socketio.server.environ[self.eio_sid] = {} socketio.server.async_handlers = False # easier to test when socketio.server.eio.async_handlers = False # events are sync if isinstance(socketio.server.manager, PubSubManager): raise RuntimeError('Test client cannot be used with a message ' 'queue. Disable the queue on your test ' 'configuration.') socketio.server.manager.initialize() self.connect(namespace=namespace, query_string=query_string, headers=headers, auth=auth) def is_connected(self, namespace=None): """Check if a namespace is connected. :param namespace: The namespace to check. The global namespace is assumed if this argument is not provided. """ return self.connected.get(namespace or '/', False) def connect(self, namespace=None, query_string=None, headers=None, auth=None): """Connect the client. :param namespace: The namespace for the client. If not provided, the client connects to the server on the global namespace. :param query_string: A string with custom query string arguments. :param headers: A dictionary with custom HTTP headers. :param auth: Optional authentication data, given as a dictionary. Note that it is usually not necessary to explicitly call this method, since a connection is automatically established when an instance of this class is created. An example where it this method would be useful is when the application accepts multiple namespace connections. """ url = '/socket.io' namespace = namespace or '/' if query_string: if query_string[0] != '?': query_string = '?' + query_string url += query_string environ = EnvironBuilder(url, headers=headers).get_environ() environ['flask.app'] = self.app if self.flask_test_client: # inject cookies from Flask if hasattr(self.flask_test_client, '_add_cookies_to_wsgi'): # flask >= 2.3 self.flask_test_client._add_cookies_to_wsgi(environ) else: # pragma: no cover # flask < 2.3 self.flask_test_client.cookie_jar.inject_wsgi(environ) self.socketio.server._handle_eio_connect(self.eio_sid, environ) pkt = packet.Packet(packet.CONNECT, auth, namespace=namespace) self.socketio.server._handle_eio_message(self.eio_sid, pkt.encode()) sid = self.socketio.server.manager.sid_from_eio_sid(self.eio_sid, namespace) if sid: self.connected[namespace] = True def disconnect(self, namespace=None): """Disconnect the client. :param namespace: The namespace to disconnect. The global namespace is assumed if this argument is not provided. """ if not self.is_connected(namespace): raise RuntimeError('not connected') pkt = packet.Packet(packet.DISCONNECT, namespace=namespace) self.socketio.server._handle_eio_message(self.eio_sid, pkt.encode()) del self.connected[namespace or '/'] def emit(self, event, *args, **kwargs): """Emit an event to the server. :param event: The event name. :param *args: The event arguments. :param callback: ``True`` if the client requests a callback, ``False`` if not. Note that client-side callbacks are not implemented, a callback request will just tell the server to provide the arguments to invoke the callback, but no callback is invoked. Instead, the arguments that the server provided for the callback are returned by this function. :param namespace: The namespace of the event. The global namespace is assumed if this argument is not provided. """ namespace = kwargs.pop('namespace', None) if not self.is_connected(namespace): raise RuntimeError('not connected') callback = kwargs.pop('callback', False) id = None if callback: self.callback_counter += 1 id = self.callback_counter pkt = packet.Packet(packet.EVENT, data=[event] + list(args), namespace=namespace, id=id) encoded_pkt = pkt.encode() if isinstance(encoded_pkt, list): for epkt in encoded_pkt: self.socketio.server._handle_eio_message(self.eio_sid, epkt) else: self.socketio.server._handle_eio_message(self.eio_sid, encoded_pkt) if self.acks is not None: ack = self.acks self.acks = None return ack['args'][0] if len(ack['args']) == 1 \ else ack['args'] def send(self, data, json=False, callback=False, namespace=None): """Send a text or JSON message to the server. :param data: A string, dictionary or list to send to the server. :param json: ``True`` to send a JSON message, ``False`` to send a text message. :param callback: ``True`` if the client requests a callback, ``False`` if not. Note that client-side callbacks are not implemented, a callback request will just tell the server to provide the arguments to invoke the callback, but no callback is invoked. Instead, the arguments that the server provided for the callback are returned by this function. :param namespace: The namespace of the event. The global namespace is assumed if this argument is not provided. """ if json: msg = 'json' else: msg = 'message' return self.emit(msg, data, callback=callback, namespace=namespace) def get_received(self, namespace=None): """Return the list of messages received from the server. Since this is not a real client, any time the server emits an event, the event is simply stored. The test code can invoke this method to obtain the list of events that were received since the last call. :param namespace: The namespace to get events from. The global namespace is assumed if this argument is not provided. """ if not self.is_connected(namespace): raise RuntimeError('not connected') namespace = namespace or '/' r = [pkt for pkt in self.queue if pkt['namespace'] == namespace] self.queue = [pkt for pkt in self.queue if pkt not in r] return r ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1734544988.0 flask_socketio-5.5.1/test_socketio.py0000664000175000017500000007330314730607134017356 0ustar00miguelmiguelimport json import time import unittest from flask import Flask, session, request, json as flask_json from flask_socketio import SocketIO, send, emit, join_room, leave_room, \ Namespace, disconnect, ConnectionRefusedError app = Flask(__name__) app.config['SECRET_KEY'] = 'secret' socketio = SocketIO(app) disconnected = None @socketio.on('connect') def on_connect(auth): if auth != {'foo': 'bar'}: # pragma: no cover return False if request.args.get('fail'): raise ConnectionRefusedError('failed!') send('connected') send(json.dumps(request.args.to_dict(flat=False))) send(json.dumps({h: request.headers[h] for h in request.headers.keys() if h not in ['Host', 'Content-Type', 'Content-Length']})) emit('dummy', to='nobody') @socketio.on('disconnect') def on_disconnect(reason): global disconnected disconnected = '/' @socketio.event(namespace='/test') def connect(): send('connected-test') send(json.dumps(request.args.to_dict(flat=False))) send(json.dumps({h: request.headers[h] for h in request.headers.keys() if h not in ['Host', 'Content-Type', 'Content-Length']})) @socketio.on('disconnect', namespace='/test') def on_disconnect_test(): global disconnected disconnected = '/test' @socketio.on('connect', namespace='/bgtest') def on_bgtest_connect(): def background_task(): socketio.emit('bgtest', namespace='/bgtest') socketio.start_background_task(background_task) @socketio.event def message(message): send(message) if message == 'test session': if not socketio.manage_session and 'a' in session: raise RuntimeError('session is being stored') if 'a' not in session: session['a'] = 'b' else: session['a'] = 'c' if message not in "test noackargs": return message @socketio.on('json') def on_json(data): send(data, json=True, broadcast=True) if not data.get('noackargs'): return data @socketio.on('message', namespace='/test') def on_message_test(message): send(message) @socketio.on('json', namespace='/test') def on_json_test(data): send(data, json=True, namespace='/test') @socketio.on('my custom event') def on_custom_event(data): emit('my custom response', data) if not data.get('noackargs'): return data @socketio.on('other custom event') @socketio.on('and another custom event') def get_request_event(data): global request_event_data request_event_data = request.event emit('my custom response', data) def get_request_event2(data): global request_event_data request_event_data = request.event emit('my custom response', data) socketio.on_event('yet another custom event', get_request_event2) @socketio.on('*') def catch_all(event, data): emit('my custom response', (event, data)) @socketio.on('my custom namespace event', namespace='/test') def on_custom_event_test(data): emit('my custom namespace response', data, namespace='/test') def on_custom_event_test2(data): emit('my custom namespace response', data, namespace='/test') socketio.on_event('yet another custom namespace event', on_custom_event_test2, namespace='/test') @socketio.on('my custom broadcast event') def on_custom_event_broadcast(data): emit('my custom response', data, broadcast=True) @socketio.on('my custom broadcast namespace event', namespace='/test') def on_custom_event_broadcast_test(data): emit('my custom namespace response', data, namespace='/test', broadcast=True) @socketio.on('join room') def on_join_room(data): join_room(data['room']) @socketio.on('leave room') def on_leave_room(data): leave_room(data['room']) @socketio.on('join room', namespace='/test') def on_join_room_namespace(data): join_room(data['room']) @socketio.on('leave room', namespace='/test') def on_leave_room_namespace(data): leave_room(data['room']) @socketio.on('my room event') def on_room_event(data): room = data.pop('room') emit('my room response', data, room=room) @socketio.on('my room namespace event', namespace='/test') def on_room_namespace_event(data): room = data.pop('room') send('room message', room=room) @socketio.on('bad response') def on_bad_response(): emit('my custom response', {'foo': socketio}) @socketio.on('bad callback') def on_bad_callback(): return {'foo': socketio} @socketio.on('changing response') def on_changing_response(): data = {'foo': 'bar'} emit('my custom response', data) data['foo'] = 'baz' return data @socketio.on('wildcard', namespace='*') def wildcard(data): emit('my custom response', data) @socketio.on_error() def error_handler(value): if isinstance(value, AssertionError): global error_testing error_testing = True else: raise value return 'error' @socketio.on('error testing') def raise_error(data): raise AssertionError() @socketio.on_error('/test') def error_handler_namespace(value): if isinstance(value, AssertionError): global error_testing_namespace error_testing_namespace = True else: raise value return 'error/test' @socketio.on("error testing", namespace='/test') def raise_error_namespace(data): raise AssertionError() @socketio.on_error_default def error_handler_default(value): if isinstance(value, AssertionError): global error_testing_default error_testing_default = True else: raise value return 'error/default' @socketio.on("error testing", namespace='/unused_namespace') def raise_error_default(data): raise AssertionError() class MyNamespace(Namespace): def on_connect(self): send('connected-ns') send(json.dumps(request.args.to_dict(flat=False))) send(json.dumps( {h: request.headers[h] for h in request.headers.keys() if h not in ['Host', 'Content-Type', 'Content-Length']})) def on_disconnect(self): global disconnected disconnected = '/ns' def on_message(self, message): send(message) if message == 'test session': session['a'] = 'b' if message not in "test noackargs": return message def on_json(self, data): send(data, json=True, broadcast=True) if not data.get('noackargs'): return data def on_exit(self, data): disconnect() def on_my_custom_event(self, data): emit('my custom response', data) if not data.get('noackargs'): return data def on_other_custom_event(self, data): global request_event_data request_event_data = request.event emit('my custom response', data) socketio.on_namespace(MyNamespace('/ns')) @app.route('/session') def session_route(): session['foo'] = 'bar' return '' class TestSocketIO(unittest.TestCase): @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): pass def setUp(self): pass def tearDown(self): pass def test_connect(self): client = socketio.test_client(app, auth={'foo': 'bar'}) client2 = socketio.test_client(app, auth={'foo': 'bar'}) self.assertTrue(client.is_connected()) self.assertTrue(client2.is_connected()) self.assertNotEqual(client.eio_sid, client2.eio_sid) received = client.get_received() self.assertEqual(len(received), 3) self.assertEqual(received[0]['args'], 'connected') self.assertEqual(received[1]['args'], '{}') self.assertEqual(received[2]['args'], '{}') client.disconnect() self.assertFalse(client.is_connected()) self.assertTrue(client2.is_connected()) client2.disconnect() self.assertFalse(client2.is_connected()) def test_connect_query_string_and_headers(self): client = socketio.test_client( app, query_string='?foo=bar&foo=baz', headers={'Authorization': 'Bearer foobar'}, auth={'foo': 'bar'}) received = client.get_received() self.assertEqual(len(received), 3) self.assertEqual(received[0]['args'], 'connected') self.assertEqual(received[1]['args'], '{"foo": ["bar", "baz"]}') self.assertEqual(received[2]['args'], '{"Authorization": "Bearer foobar"}') client.disconnect() def test_connect_namespace(self): client = socketio.test_client(app, namespace='/test') self.assertTrue(client.is_connected('/test')) received = client.get_received('/test') self.assertEqual(len(received), 3) self.assertEqual(received[0]['args'], 'connected-test') self.assertEqual(received[1]['args'], '{}') self.assertEqual(received[2]['args'], '{}') client.disconnect(namespace='/test') self.assertFalse(client.is_connected('/test')) def test_connect_namespace_query_string_and_headers(self): client = socketio.test_client( app, namespace='/test', query_string='foo=bar', headers={'My-Custom-Header': 'Value'}) received = client.get_received('/test') self.assertEqual(len(received), 3) self.assertEqual(received[0]['args'], 'connected-test') self.assertEqual(received[1]['args'], '{"foo": ["bar"]}') self.assertEqual(received[2]['args'], '{"My-Custom-Header": "Value"}') client.disconnect(namespace='/test') def test_connect_rejected(self): client = socketio.test_client(app, query_string='fail=1', auth={'foo': 'bar'}) self.assertFalse(client.is_connected()) def test_disconnect(self): global disconnected disconnected = None client = socketio.test_client(app, auth={'foo': 'bar'}) client.disconnect() self.assertEqual(disconnected, '/') def test_disconnect_namespace(self): global disconnected disconnected = None client = socketio.test_client(app, namespace='/test') client.disconnect('/test') self.assertEqual(disconnected, '/test') def test_message_queue_options(self): app = Flask(__name__) socketio = SocketIO(app, message_queue='redis://') self.assertFalse(socketio.server_options['client_manager'].write_only) app = Flask(__name__) socketio = SocketIO(app) socketio.init_app(app, message_queue='redis://') self.assertFalse(socketio.server_options['client_manager'].write_only) app = Flask(__name__) socketio = SocketIO(message_queue='redis://') self.assertTrue(socketio.server_options['client_manager'].write_only) app = Flask(__name__) socketio = SocketIO() socketio.init_app(None, message_queue='redis://') self.assertTrue(socketio.server_options['client_manager'].write_only) def test_send(self): client = socketio.test_client(app, auth={'foo': 'bar'}) client.get_received() client.send('echo this message back') received = client.get_received() self.assertEqual(len(received), 1) self.assertEqual(received[0]['args'], 'echo this message back') def test_send_json(self): client1 = socketio.test_client(app, auth={'foo': 'bar'}) client2 = socketio.test_client(app, auth={'foo': 'bar'}) client1.get_received() client2.get_received() client1.send({'a': 'b'}, json=True) received = client1.get_received() self.assertEqual(len(received), 1) self.assertEqual(received[0]['args']['a'], 'b') received = client2.get_received() self.assertEqual(len(received), 1) self.assertEqual(received[0]['args']['a'], 'b') def test_send_namespace(self): client = socketio.test_client(app, namespace='/test') client.get_received('/test') client.send('echo this message back', namespace='/test') received = client.get_received('/test') self.assertTrue(len(received) == 1) self.assertTrue(received[0]['args'] == 'echo this message back') def test_send_json_namespace(self): client = socketio.test_client(app, namespace='/test') client.get_received('/test') client.send({'a': 'b'}, json=True, namespace='/test') received = client.get_received('/test') self.assertEqual(len(received), 1) self.assertEqual(received[0]['args']['a'], 'b') def test_emit(self): client = socketio.test_client(app, auth={'foo': 'bar'}) client.get_received() client.emit('my custom event', {'a': 'b'}) received = client.get_received() self.assertEqual(len(received), 1) self.assertEqual(len(received[0]['args']), 1) self.assertEqual(received[0]['name'], 'my custom response') self.assertEqual(received[0]['args'][0]['a'], 'b') def test_emit_binary(self): client = socketio.test_client(app, auth={'foo': 'bar'}) client.get_received() client.emit('my custom event', {'a': b'\x01\x02\x03'}) received = client.get_received() self.assertEqual(len(received), 1) self.assertEqual(len(received[0]['args']), 1) self.assertEqual(received[0]['name'], 'my custom response') self.assertEqual(received[0]['args'][0]['a'], b'\x01\x02\x03') def test_emit_catch_all_event(self): client = socketio.test_client(app, auth={'foo': 'bar'}) client.get_received() client.emit('random event', {'foo': 'bar'}) received = client.get_received() self.assertEqual(len(received), 1) self.assertEqual(len(received[0]['args']), 2) self.assertEqual(received[0]['name'], 'my custom response') self.assertEqual(received[0]['args'][0], 'random event') self.assertEqual(received[0]['args'][1], {'foo': 'bar'}) def test_send_catch_all_namespace(self): client = socketio.test_client(app, namespace='/test') client.get_received('/test') client.emit('wildcard', {'a': 'b'}, namespace='/test') received = client.get_received('/test') self.assertEqual(len(received), 1) self.assertEqual(len(received[0]['args']), 1) self.assertEqual(received[0]['name'], 'my custom response') self.assertEqual(received[0]['args'][0]['a'], 'b') def test_request_event_data(self): client = socketio.test_client(app, auth={'foo': 'bar'}) client.get_received() global request_event_data request_event_data = None client.emit('other custom event', 'foo') expected_data = {'message': 'other custom event', 'args': ('foo',)} self.assertEqual(request_event_data, expected_data) client.emit('and another custom event', 'bar') expected_data = {'message': 'and another custom event', 'args': ('bar',)} self.assertEqual(request_event_data, expected_data) def test_emit_namespace(self): client = socketio.test_client(app, namespace='/test') client.get_received('/test') client.emit('my custom namespace event', {'a': 'b'}, namespace='/test') received = client.get_received('/test') self.assertEqual(len(received), 1) self.assertEqual(len(received[0]['args']), 1) self.assertEqual(received[0]['name'], 'my custom namespace response') self.assertEqual(received[0]['args'][0]['a'], 'b') def test_broadcast(self): client1 = socketio.test_client(app, auth={'foo': 'bar'}) client2 = socketio.test_client(app, auth={'foo': 'bar'}) client3 = socketio.test_client(app, namespace='/test') client2.get_received() client3.get_received('/test') client1.emit('my custom broadcast event', {'a': 'b'}, broadcast=True) received = client2.get_received() self.assertEqual(len(received), 1) self.assertEqual(len(received[0]['args']), 1) self.assertEqual(received[0]['name'], 'my custom response') self.assertEqual(received[0]['args'][0]['a'], 'b') self.assertEqual(len(client3.get_received('/test')), 0) def test_broadcast_namespace(self): client1 = socketio.test_client(app, namespace='/test') client2 = socketio.test_client(app, namespace='/test') client3 = socketio.test_client(app, auth={'foo': 'bar'}) client2.get_received('/test') client3.get_received() client1.emit('my custom broadcast namespace event', {'a': 'b'}, namespace='/test') received = client2.get_received('/test') self.assertEqual(len(received), 1) self.assertEqual(len(received[0]['args']), 1) self.assertEqual(received[0]['name'], 'my custom namespace response') self.assertEqual(received[0]['args'][0]['a'], 'b') self.assertEqual(len(client3.get_received()), 0) def test_managed_session(self): flask_client = app.test_client() flask_client.get('/session') client = socketio.test_client(app, flask_test_client=flask_client, auth={'foo': 'bar'}) client.get_received() client.send('echo this message back') self.assertEqual( socketio.server.environ[client.eio_sid]['saved_session'], {'foo': 'bar'}) client.send('test session') self.assertEqual( socketio.server.environ[client.eio_sid]['saved_session'], {'a': 'b', 'foo': 'bar'}) client.send('test session') self.assertEqual( socketio.server.environ[client.eio_sid]['saved_session'], {'a': 'c', 'foo': 'bar'}) def test_unmanaged_session(self): socketio.manage_session = False flask_client = app.test_client() flask_client.get('/session') client = socketio.test_client(app, flask_test_client=flask_client, auth={'foo': 'bar'}) client.get_received() client.send('test session') client.send('test session') socketio.manage_session = True def test_room(self): client1 = socketio.test_client(app, auth={'foo': 'bar'}) client2 = socketio.test_client(app, auth={'foo': 'bar'}) client3 = socketio.test_client(app, namespace='/test') client1.get_received() client2.get_received() client3.get_received('/test') client1.emit('join room', {'room': 'one'}) client2.emit('join room', {'room': 'one'}) client3.emit('join room', {'room': 'one'}, namespace='/test') client1.emit('my room event', {'a': 'b', 'room': 'one'}) received = client1.get_received() self.assertEqual(len(received), 1) self.assertEqual(len(received[0]['args']), 1) self.assertEqual(received[0]['name'], 'my room response') self.assertEqual(received[0]['args'][0]['a'], 'b') self.assertEqual(received, client2.get_received()) received = client3.get_received('/test') self.assertEqual(len(received), 0) client1.emit('leave room', {'room': 'one'}) client1.emit('my room event', {'a': 'b', 'room': 'one'}) received = client1.get_received() self.assertEqual(len(received), 0) received = client2.get_received() self.assertEqual(len(received), 1) self.assertEqual(len(received[0]['args']), 1) self.assertEqual(received[0]['name'], 'my room response') self.assertEqual(received[0]['args'][0]['a'], 'b') client2.disconnect() socketio.emit('my room event', {'a': 'b'}, room='one') received = client1.get_received() self.assertEqual(len(received), 0) received = client3.get_received('/test') self.assertEqual(len(received), 0) client3.emit('my room namespace event', {'room': 'one'}, namespace='/test') received = client3.get_received('/test') self.assertEqual(len(received), 1) self.assertEqual(received[0]['name'], 'message') self.assertEqual(received[0]['args'], 'room message') socketio.close_room('one', namespace='/test') client3.emit('my room namespace event', {'room': 'one'}, namespace='/test') received = client3.get_received('/test') self.assertEqual(len(received), 0) def test_error_handling(self): client = socketio.test_client(app, auth={'foo': 'bar'}) client.get_received() global error_testing error_testing = False client.emit("error testing", "") self.assertTrue(error_testing) def test_error_handling_namespace(self): client = socketio.test_client(app, namespace='/test') client.get_received('/test') global error_testing_namespace error_testing_namespace = False client.emit("error testing", "", namespace='/test') self.assertTrue(error_testing_namespace) def test_error_handling_default(self): client = socketio.test_client(app, namespace='/unused_namespace') client.get_received('/unused_namespace') global error_testing_default error_testing_default = False client.emit("error testing", "", namespace='/unused_namespace') self.assertTrue(error_testing_default) def test_ack(self): client1 = socketio.test_client(app, auth={'foo': 'bar'}) client2 = socketio.test_client(app, auth={'foo': 'bar'}) client3 = socketio.test_client(app, auth={'foo': 'bar'}) ack = client1.send('echo this message back', callback=True) self.assertEqual(ack, 'echo this message back') ack = client1.send('test noackargs', callback=True) # python-socketio releases before 1.5 did not correctly implement # callbacks with no arguments. Here we check for [] (the correct, 1.5 # and up response) and None (the wrong pre-1.5 response). self.assertTrue(ack == [] or ack is None) ack2 = client2.send({'a': 'b'}, json=True, callback=True) self.assertEqual(ack2, {'a': 'b'}) ack3 = client3.emit('my custom event', {'a': 'b'}, callback=True) self.assertEqual(ack3, {'a': 'b'}) def test_noack(self): client1 = socketio.test_client(app, auth={'foo': 'bar'}) client2 = socketio.test_client(app, auth={'foo': 'bar'}) client3 = socketio.test_client(app, auth={'foo': 'bar'}) no_ack_dict = {'noackargs': True} noack = client1.send("test noackargs", callback=False) self.assertIsNone(noack) noack2 = client2.send(no_ack_dict, json=True, callback=False) self.assertIsNone(noack2) noack3 = client3.emit('my custom event', no_ack_dict) self.assertIsNone(noack3) def test_error_handling_ack(self): client1 = socketio.test_client(app, auth={'foo': 'bar'}) client2 = socketio.test_client(app, namespace='/test') client3 = socketio.test_client(app, namespace='/unused_namespace') errorack = client1.emit("error testing", "", callback=True) self.assertEqual(errorack, 'error') errorack_namespace = client2.emit("error testing", "", namespace='/test', callback=True) self.assertEqual(errorack_namespace, 'error/test') errorack_default = client3.emit("error testing", "", namespace='/unused_namespace', callback=True) self.assertEqual(errorack_default, 'error/default') def test_on_event(self): client = socketio.test_client(app, auth={'foo': 'bar'}) client.get_received() global request_event_data request_event_data = None client.emit('yet another custom event', 'foo') expected_data = {'message': 'yet another custom event', 'args': ('foo',)} self.assertEqual(request_event_data, expected_data) client = socketio.test_client(app, namespace='/test') client.get_received('/test') client.emit('yet another custom namespace event', {'a': 'b'}, namespace='/test') received = client.get_received('/test') self.assertEqual(len(received), 1) self.assertEqual(len(received[0]['args']), 1) self.assertEqual(received[0]['name'], 'my custom namespace response') self.assertEqual(received[0]['args'][0]['a'], 'b') def test_connect_class_based(self): client = socketio.test_client(app, namespace='/ns') received = client.get_received('/ns') self.assertEqual(len(received), 3) self.assertEqual(received[0]['args'], 'connected-ns') self.assertEqual(received[1]['args'], '{}') self.assertEqual(received[2]['args'], '{}') client.disconnect('/ns') def test_connect_class_based_query_string_and_headers(self): client = socketio.test_client( app, namespace='/ns', query_string='foo=bar', headers={'Authorization': 'Basic foobar'}) received = client.get_received('/ns') self.assertEqual(len(received), 3) self.assertEqual(received[0]['args'], 'connected-ns') self.assertEqual(received[1]['args'], '{"foo": ["bar"]}') self.assertEqual(received[2]['args'], '{"Authorization": "Basic foobar"}') client.disconnect('/ns') def test_disconnect_class_based(self): global disconnected disconnected = None client = socketio.test_client(app, namespace='/ns') client.disconnect('/ns') self.assertEqual(disconnected, '/ns') def test_send_class_based(self): client = socketio.test_client(app, namespace='/ns') client.get_received('/ns') client.send('echo this message back', namespace='/ns') received = client.get_received('/ns') self.assertTrue(len(received) == 1) self.assertTrue(received[0]['args'] == 'echo this message back') def test_send_json_class_based(self): client = socketio.test_client(app, namespace='/ns') client.get_received('/ns') client.send({'a': 'b'}, json=True, namespace='/ns') received = client.get_received('/ns') self.assertEqual(len(received), 1) self.assertEqual(received[0]['args']['a'], 'b') def test_server_disconnected(self): client = socketio.test_client(app, namespace='/ns') client2 = socketio.test_client(app, namespace='/ns') client.get_received('/ns') client2.get_received('/ns') client.emit('exit', {}, namespace='/ns') self.assertFalse(client.is_connected('/ns')) self.assertTrue(client2.is_connected('/ns')) with self.assertRaises(RuntimeError): client.emit('hello', {}, namespace='/ns') client2.emit('exit', {}, namespace='/ns') self.assertFalse(client2.is_connected('/ns')) with self.assertRaises(RuntimeError): client2.emit('hello', {}, namespace='/ns') def test_emit_class_based(self): client = socketio.test_client(app, namespace='/ns') client.get_received('/ns') client.emit('my_custom_event', {'a': 'b'}, namespace='/ns') received = client.get_received('/ns') self.assertEqual(len(received), 1) self.assertEqual(len(received[0]['args']), 1) self.assertEqual(received[0]['name'], 'my custom response') self.assertEqual(received[0]['args'][0]['a'], 'b') def test_request_event_data_class_based(self): client = socketio.test_client(app, namespace='/ns') client.get_received('/ns') global request_event_data request_event_data = None client.emit('other_custom_event', 'foo', namespace='/ns') expected_data = {'message': 'other_custom_event', 'args': ('foo',)} self.assertEqual(request_event_data, expected_data) def test_delayed_init(self): app = Flask(__name__) socketio = SocketIO(allow_upgrades=False, json=flask_json) @socketio.on('connect') def on_connect(): send({'connected': 'foo'}, json=True) socketio.init_app(app, cookie='foo') self.assertFalse(socketio.server.eio.allow_upgrades) self.assertEqual(socketio.server.eio.cookie, 'foo') client = socketio.test_client(app, auth={'foo': 'bar'}) received = client.get_received() self.assertEqual(len(received), 1) self.assertEqual(received[0]['args'], {'connected': 'foo'}) def test_encode_decode(self): client = socketio.test_client(app, auth={'foo': 'bar'}) client.get_received() data = {'foo': 'bar', 'invalid': socketio} self.assertRaises(TypeError, client.emit, 'my custom event', data, callback=True) data = {'foo': 'bar'} ack = client.emit('my custom event', data, callback=True) data['foo'] = 'baz' received = client.get_received() self.assertEqual(ack, {'foo': 'bar'}) self.assertEqual(len(received), 1) self.assertEqual(received[0]['args'][0], {'foo': 'bar'}) def test_encode_decode_2(self): client = socketio.test_client(app, auth={'foo': 'bar'}) self.assertRaises(TypeError, client.emit, 'bad response') self.assertRaises(TypeError, client.emit, 'bad callback', callback=True) client.get_received() ack = client.emit('changing response', callback=True) received = client.get_received() self.assertEqual(len(received), 1) self.assertEqual(received[0]['args'][0], {'foo': 'bar'}) self.assertEqual(ack, {'foo': 'baz'}) def test_background_task(self): client = socketio.test_client(app, namespace='/bgtest') self.assertTrue(client.is_connected(namespace='/bgtest')) time.sleep(0.1) received = client.get_received('/bgtest') self.assertEqual(len(received), 1) self.assertEqual(received[0]['name'], 'bgtest') if __name__ == '__main__': unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1730029461.0 flask_socketio-5.5.1/tox.ini0000664000175000017500000000117714707423625015445 0ustar00miguelmiguel[tox] envlist=flake8,py38,py39,py310,py311,py312,pypy3,docs skip_missing_interpreters=True [gh-actions] python = 3.6: py36 3.7: py37 3.8: py38 3.9: py39 3.10: py310 3.11: py311 pypy-3: pypy3 [testenv] commands= pip install -e . pytest -p no:logging --cov=flask_socketio --cov-branch --cov-report=term-missing --cov-report=xml deps= pytest pytest-cov redis [testenv:flake8] commands= flake8 --exclude=".*" --ignore=W503,E402,E722 src/flask_socketio test_socketio.py deps= flake8 [testenv:docs] changedir=docs deps= sphinx allowlist_externals= make commands= make html