Socket.IO integration for Flask applications.

Overview

Flask-SocketIO

Build status codecov

Socket.IO integration for Flask applications.

Installation

You can install this package as usual with pip:

pip install flask-socketio

Example

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

Comments
  • SocketIO:  Video Streaming from server to client

    SocketIO: Video Streaming from server to client

    Dear Miguel:

    Hello

    This is from your video streaming page + emit , server side (i removed the Return):

    @app.route('/video_feed')
    def video_feed():
           socketio.emit('from_flask', Response(gen(), mimetype='multipart/x-mixed-replace; 
                                                    boundary=frame'),namespace='/test')
    

    here the problems are Response and the Generator mixing with the event-driven SocketIO

    client

     socket.on('from_flask', function (data) { 
              $("#image").attr("src",data) ;
               });
    

    html

    <img id="image" src="video_feed">

    Would you please help me ? i know something is wrong here but i cant't figure it

    Thanks a million for your great work

    question 
    opened by Fizmath 64
  • Running With Gunicorn won't request 3rd party APIs? running with flask run gives results okay

    Running With Gunicorn won't request 3rd party APIs? running with flask run gives results okay

    Hello Miguel, My requirement. I'm building an app for a chatbot. The flask app will receive messages from the front-end via javascript socket-io and query that message to a remote NLP model through API. When I'm running the app with flask run command the api works correctly but when I run it with gunicorn --worker-class eventlet -w 1 module:app the API doesn't work. Since my server isn't showing any errors. Neither it is crashing it just returns the default message which I have written to print if the API isn't run.

    question 
    opened by Ahzam-Lathiya 58
  • Session disconnected causes the thread handling eventlet + redis packets/events

    Session disconnected causes the thread handling eventlet + redis packets/events

    Hi Miguel,

    I'm encountering with eventlet + redis, after receiving the following error, it won't be able to do an "emit"/"send" events to the future clients anymore

    Exception in thread Thread-1:
    Traceback (most recent call last):
      File "/usr/local/lib/python3.5/threading.py", line 914, in _bootstrap_inner
        self.run()
      File "/usr/local/lib/python3.5/threading.py", line 862, in run
        self._target(*self._args, **self._kwargs)
      File "/home/vf/env/lib/python3.5/site-packages/socketio/pubsub_manager.py", line 143, in _thread
        self._handle_emit(data)
      File "/home/vf/env/lib/python3.5/site-packages/socketio/pubsub_manager.py", line 101, in _handle_emit
        callback=callback)
      File "/home/vf/env/lib/python3.5/site-packages/socketio/base_manager.py", line 103, in emit
        self.server._emit_internal(sid, event, data, namespace, id)
      File "/home/vf/env/lib/python3.5/site-packages/socketio/server.py", line 322, in _emit_internal
        binary=binary))
      File "/home/vf/env/lib/python3.5/site-packages/socketio/server.py", line 333, in _send_packet
        self.eio.send(sid, encoded_packet, binary=False)
      File "/home/vf/env/lib/python3.5/site-packages/engineio/server.py", line 158, in send
        self._get_socket(sid).send(packet.Packet(packet.MESSAGE, data=data,
      File "/home/vf/env/lib/python3.5/site-packages/engineio/server.py", line 344, in _get_socket
        raise KeyError('Session is disconnected')
    KeyError: 'Session is disconnected'
    
    investigate 
    opened by cmabastar 55
  • Possible to emit from a Celery task in Flask?

    Possible to emit from a Celery task in Flask?

    Trying to emit from a Celery task in Flask. Not sure if this is possible. Here's my simplified code:

    @celery.task()
    def do_stuff():
        logger.info('emmittting')
        socketio.emit('my response', {'data': user_cache_key})
    

    I'm using Gunicorn + Celery + SocketIO + Redis (broker + result backend for Celery). Is this even possible? I'm not sure if gevent can communicate to/from a celery worker.

    I'm hoping to use websockets to track the progress of long-running Celery tasks.

    enhancement question 
    opened by johnboiles 55
  • start_background_task

    start_background_task

    Hi Miguel,

    really awesome project.

    I have a problem when use the Flask-SocketIO. I wanna start a background task automatic when the socketio server begins to run. The background task can continuously broadcast the message to client by using emit(). But the socketio.start_background_task() is not a decorator, it seems cannot start the background task with the socketio server starting. Moreover, I have a requirement which is starting some background tasks in right time. Are you planning to become the method start_background_task() to a decorator, and integrate a APScheduler compatibility?

    Thanks! Keep up the good work!

    question 
    opened by shitone 53
  • Session disconnected issue

    Session disconnected issue

    Hi, when using Flask-SocketIO I occasionally get the following error on the backend

    Traceback (most recent call last):
      File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/gevent-1.1b5-py2.7-macosx-10.6-intel.egg/gevent/pywsgi.py", line 792, in handle_one_response
        self.run_application()
      File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/gevent-1.1b5-py2.7-macosx-10.6-intel.egg/gevent/pywsgi.py", line 778, in run_application
        self.result = self.application(self.environ, self.start_response)
      File "/Library/Python/2.7/site-packages/flask/app.py", line 1836, in __call__
        return self.wsgi_app(environ, start_response)
      File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/flask_socketio/__init__.py", line 37, in __call__
        start_response)
      File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/engineio/middleware.py", line 47, in __call__
        return self.engineio_app.handle_request(environ, start_response)
      File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/socketio/server.py", line 303, in handle_request
        return self.eio.handle_request(environ, start_response)
      File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/engineio/server.py", line 242, in handle_request
        socket = self._get_socket(sid)
      File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/engineio/server.py", line 340, in _get_socket
        raise KeyError('Session is disconnected')
    

    It seems to be related to the server being occupied and so being unable to deal with emits from the front-end, but I actually don't do any emits from the front-end, any suggestions?

    It also reconnects after about a half-second, but it's still not great UX-wise

    investigate 
    opened by DecSander 47
  • Socket.io not working on my machine

    Socket.io not working on my machine

    I'm new in developing and Flask I had 2 projects during my course , the error occurs in the second one only and only when socket.io exist , it's an empty project but Flask behaves very weird.

    for example, every time I run Flask without socket IO it reads something like this

    D:\WORK\study sc5\project1\project1>flask run
    Serving Flask app "hello"
    Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
    

    in project 2 we had to work with socket.io and I know it's the reason because I deleted its line and the weird behavior were gone , also no errors when I ran the socket IO application I get

    D:\WORK\study sc5\project2\project2>flask run
     * Serving Flask-SocketIO app "application"
    

    that is it after a while I get

    [WinError 10053] An established connection was aborted by the software in your host machine
    Sun Oct  7 23:47:57 2018 {'REMOTE_ADDR': '127.0.0.1', 'REMOTE_PORT': '56449', 'HTTP_HOST': '127.0.0.1:5000', (hidden keys: 23)} failed with ConnectionAbortedError
    

    with that said here is my simple python code

    
    import os, passlib ,requests ,time
    
    from flask import Flask, session , render_template , request,redirect,url_for
    from flask_socketio import SocketIO, emit ,join_room, leave_room , Namespace
    from datetime import date , datetime
    from flask_session import Session
    from sqlalchemy import create_engine
    from sqlalchemy.orm import scoped_session, sessionmaker
    from passlib.hash import sha256_crypt
    
    
    engine = create_engine("postgres:**************************",echo=True)
    db = scoped_session(sessionmaker(bind=engine))
    
    
    
    app = Flask(__name__)
    app.config["SECRET_KEY"] = 'secrettt'
    #sess.init_app(app)
    socketio = SocketIO(app)
    
    class NRoom:
        def __init__(self,Rowner,Rname,Rpw):
            self.Rowner = Rowner
            self.Rname = Rname
            self.Rpw = Rpw
    
    
    class MyCustomNamespace(Namespace):
    def on_connect(self):
        pass
    
    def on_disconnect(self):
        pass
    
    def on_my_event(self, data):
        emit('my_response', data)
    
    socketio.on_namespace(MyCustomNamespace('/test'))
    
    
    @socketio.on('message')
    def handle(msg):
        print(f'\n\n\n Message:{msg}\n\n\n' )
        send(msg, broadcast=True)
    
    
    @app.route("/")
    def index():
        return render_template("index.html")
    
    @app.route("/guest" , methods = ["GET" , "POST"])
    def guest():
    
        if request.method == "POST":
        nickname = request.form.get("guestname")
        session["user"] = nickname
        print(f"\n\n\n {nickname} \n\n\n\n ")
    
        return redirect(url_for('guest',guestname=nickname))
    else:
    
    
        return render_template("guest.html")
    

    index html file

    <!DOCTYPE html>
        <html>
            <head>
                <meta charset="utf-8">
                <meta name="viewport" content="width=device-width">
                <title>welcome bk</title>
            </head>
            <body>
                <script type="text/javascript" src="{{url_for('static', filename='javascript.js')}}"></script>
                <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
                <script type="text/javascript" charset="utf-8">
    
                var socket = io.connect('http://' + document.domain + ':' + location.port);
                socket.on('connect', function() {
                socket.emit('my event', {data: 'I\'m connected!'});
                });
            </script>
    
    
            <script>
    
                    document.addEventListener('DOMCOntentLoaded',function(){
    
                        var socket = io.connect('http://127.0.0.1:5000');
    
                        socket.on('connect',function() {
                            socket.send("test socketio have passed ! ");
    
                        });
                    });
    
            </script>
            <form action="{{ url_for('login') }}">
                 <input type="submit" value="login" />
            </form>
    
            <form action="{{ url_for('regist') }}">
                 <input type="submit" value="regist" />
            </form>
    
    
            <form action="{{ url_for('guest') }}">
                 <input type="submit" value="login as guest" />
            </form>
        </body>
    </html>
    

    tested it with chrome and Firefox

    question 
    opened by ll-M-ll 43
  • IOError: unable to complete websocket handshake while running in  uwsgi+Nginx

    IOError: unable to complete websocket handshake while running in uwsgi+Nginx

    I have been planning to deploy a flask-SocketIO application into production using uwsgi server behind Nginx

    Versions including relevant dependencies of my virtual environment:-

    OS:-  Ubuntu 16.04.3 LTS
    uWsgi:-   2.0.15 
    nginx:-   1.12.2
    python:- 2.7.12
    Falsk:-   0.12.2
    Flask-SocketIO:-  2.9.2
    gevent:- 1.2.2
    
    

    I am intended to run the uwsgi server through systemd and load the uwsgi configurations from a .ini file.

    Here's my wsgi.py file:

    from server import app
    if __name__ == "__main__":
        app.run()
    

    Here's the configuration file myproject.ini for uwsgi

    [uwsgi]
    module = wsgi:app
    
    http = :5000
    gevent = 1000
    http-websockets = true
    
    master = true
    processes = 5
    
    socket = myproject.sock
    chmod-socket = 660
    vacuum = true
    
    die-on-term = true
    

    Here's the myproject.service file in /etc/systemd/system

    [Unit]
    Description=uWSGI instance to serve myproject
    After=network.target
    
    [Service]
    User=user
    Group=www-data
    WorkingDirectory=/home/user/myproject
    Environment="PATH=/home/user/myproject/virtual_frame/bin"
    ExecStart=/home/user/myproject/virtual_frame/bin/uwsgi --ini myproject.ini
    
    [Install]
    WantedBy=multi-user.target
    

    And, finally my nginx configuration file:

     server {
        listen 80;
        server_name 10.11.201.82:5000;
    
        location / {
            include uwsgi_params;
            uwsgi_pass unix:/home/user/myproject/myproject.sock;
            uwsgi_ignore_client_abort on;
        }
    
        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://10.11.201.82:5000/socket.io;
        }
    
    }
    

    Errors:-

    Actually I'm getting different errors from several times.

    1) IOError: unable to complete websocket handshake

    Here's my project status while running:_

    user@user-HVM-domU:~/myproject$ sudo journalctl -u myproject -n 20
    -- Logs begin at শনি 2018-02-03 09:52:05 +06, end at রবি 2018-02-04 15:27:48 +06. --
    ফেব্রু 04 15:27:39 user-HVM-domU uwsgi[23592]:   File "/home/user/myproject/virtual_frame/local/lib/python2.7/site-packages/flask/app.py", line 1997, i
    ফেব্রু 04 15:27:39 user-HVM-domU uwsgi[23592]:     return self.wsgi_app(environ, start_response)
    ফেব্রু 04 15:27:39 user-HVM-domU uwsgi[23592]:   File "/home/user/myproject/virtual_frame/local/lib/python2.7/site-packages/flask_socketio/__init__.py"
    ফেব্রু 04 15:27:39 user-HVM-domU uwsgi[23592]:     start_response)
    ফেব্রু 04 15:27:39 user-HVM-domU uwsgi[23592]:   File "/home/user/myproject/virtual_frame/local/lib/python2.7/site-packages/engineio/middleware.py", li
    ফেব্রু 04 15:27:39 user-HVM-domU uwsgi[23592]:     return self.engineio_app.handle_request(environ, start_response)
    ফেব্রু 04 15:27:39 user-HVM-domU uwsgi[23592]:   File "/home/user/myproject/virtual_frame/local/lib/python2.7/site-packages/socketio/server.py", line 3
    ফেব্রু 04 15:27:39 user-HVM-domU uwsgi[23592]:     return self.eio.handle_request(environ, start_response)
    ফেব্রু 04 15:27:39 user-HVM-domU uwsgi[23592]:   File "/home/user/myproject/virtual_frame/local/lib/python2.7/site-packages/engineio/server.py", line 2
    ফেব্রু 04 15:27:39 user-HVM-domU uwsgi[23592]:     environ, start_response)
    ফেব্রু 04 15:27:39 user-HVM-domU uwsgi[23592]:   File "/home/user/myproject/virtual_frame/local/lib/python2.7/site-packages/engineio/socket.py", line 8
    ফেব্রু 04 15:27:39 user-HVM-domU uwsgi[23592]:     start_response)
    ফেব্রু 04 15:27:39 user-HVM-domU uwsgi[23592]:   File "/home/user/myproject/virtual_frame/local/lib/python2.7/site-packages/engineio/socket.py", line 1
    ফেব্রু 04 15:27:39 user-HVM-domU uwsgi[23592]:     return ws(environ, start_response)
    ফেব্রু 04 15:27:39 user-HVM-domU uwsgi[23592]:   File "/home/user/myproject/virtual_frame/local/lib/python2.7/site-packages/engineio/async_gevent_uwsgi
    ফেব্রু 04 15:27:39 user-HVM-domU uwsgi[23592]:     uwsgi.websocket_handshake()
    ফেব্রু 04 15:27:39 user-HVM-domU uwsgi[23592]: IOError: unable to complete websocket handshake
    ফেব্রু 04 15:27:39 user-HVM-domU uwsgi[23592]: [pid: 23604|app: 0|req: 21/79] 10.11.201.82 () {50 vars in 1028 bytes} [Sun Feb  4 15:27:39 2018] GET /s
    ফেব্রু 04 15:27:39 user-HVM-domU uwsgi[23592]: [pid: 23604|app: 0|req: 22/80] 10.11.201.82 () {38 vars in 784 bytes} [Sun Feb  4 15:27:39 2018] GET /so
    ফেব্রু 04 15:27:39 user-HVM-domU uwsgi[23592]: [pid: 23604|app: 0|req: 23/81] 10.11.201.82 () {42 vars in 845 bytes} [Sun Feb  4 15:27:39 2018]
    

    2) IOError: write error: uwsgi_response_writev_headers_and_body_do(): Broken pipe [core/writer.

    ফেব্রু 04 15:16:53 user-HVM-domU uwsgi[23421]: [pid: 23433|app: 0|req: 52/94] 10.11.201.82 () {42 vars in 845 bytes} [Sun Feb  4 15:16:38 2018] POST /s
    ফেব্রু 04 15:16:53 user-HVM-domU uwsgi[23421]: [pid: 23433|app: 0|req: 52/95] 10.11.201.82 () {38 vars in 783 bytes} [Sun Feb  4 15:16:30 2018] GET /so
    ফেব্রু 04 15:16:55 user-HVM-domU uwsgi[23421]: [pid: 23433|app: 0|req: 54/96] 10.11.201.82 () {42 vars in 843 bytes} [Sun Feb  4 15:16:55 2018] POST /s
    ফেব্রু 04 15:16:55 user-HVM-domU uwsgi[23421]: [pid: 23433|app: 0|req: 54/97] 10.11.201.82 () {38 vars in 783 bytes} [Sun Feb  4 15:16:53 2018] GET /so
    ফেব্রু 04 15:17:08 user-HVM-domU uwsgi[23421]: Sun Feb  4 15:17:08 2018 - uwsgi_response_writev_headers_and_body_do(): Broken pipe [core/writer.c line 
    ফেব্রু 04 15:17:08 user-HVM-domU uwsgi[23421]: IOError: write error
    ফেব্রু 04 15:17:08 user-HVM-domU uwsgi[23421]: [pid: 23433|app: 0|req: 55/98] 10.11.201.82 () {44 vars in 867 bytes} [Sun Feb  4 15:16:08 2018] GET /so
    
    

    3) Nginx error log

    Last 20 line of /var/log/nginx/error.log

    2018/02/04 15:24:42 [error] 23563#23563: *109 upstream prematurely closed connection while reading response header from upstream, client: 10.11.201.82, server: 10.11.201.82, request: "GET /socket.io/?EIO=3&transport=websocket&sid=b95aa3f7a7374706a7d09d857c1e69fe HTTP/1.1", upstream: "http://10.11.201.82:5000/socket.io/?EIO=3&transport=websocket&sid=b95aa3f7a7374706a7d09d857c1e69fe", host: "10.11.201.82"
    2018/02/04 15:25:40 [error] 23560#23560: *83 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 10.11.201.82, server: 10.11.201.82, request: "GET /socket.io/?EIO=3&transport=polling&t=1517736280486-2&sid=998d555f29cc49f3949bf080b5c2820c HTTP/1.1", upstream: "http://10.11.201.82:5000/socket.io/?EIO=3&transport=polling&t=1517736280486-2&sid=998d555f29cc49f3949bf080b5c2820c", host: "10.11.201.82", referrer: "http://10.11.201.82/"
    2018/02/04 15:25:49 [error] 23563#23563: *98 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 10.11.201.82, server: 10.11.201.82, request: "GET /socket.io/?EIO=3&transport=polling&t=1517736289238-36&sid=6535da975fee43bdb49be5f061e04522 HTTP/1.1", upstream: "http://10.11.201.82:5000/socket.io/?EIO=3&transport=polling&t=1517736289238-36&sid=6535da975fee43bdb49be5f061e04522", host: "10.11.201.82", referrer: "http://10.11.201.82/"
    2018/02/04 15:25:50 [error] 23563#23563: *138 upstream prematurely closed connection while reading response header from upstream, client: 10.11.201.82, server: 10.11.201.82, request: "GET /socket.io/?EIO=3&transport=polling&t=1517736290606-40&sid=c13d0711b34b49cb8d5d973642369c33 HTTP/1.1", upstream: "http://10.11.201.82:5000/socket.io/?EIO=3&transport=polling&t=1517736290606-40&sid=c13d0711b34b49cb8d5d973642369c33", host: "10.11.201.82", referrer: "http://10.11.201.82/"
    2018/02/04 15:25:54 [error] 23563#23563: *143 upstream prematurely closed connection while reading response header from upstream, client: 10.11.201.82, server: 10.11.201.82, request: "GET /socket.io/?EIO=3&transport=polling&t=1517736294273-52&sid=aec315362ea644fe93035f7d8c5519a6 HTTP/1.1", upstream: "http://10.11.201.82:5000/socket.io/?EIO=3&transport=polling&t=1517736294273-52&sid=aec315362ea644fe93035f7d8c5519a6", host: "10.11.201.82", referrer: "http://10.11.201.82/"
    2018/02/04 15:25:56 [error] 23560#23560: *83 upstream prematurely closed connection while reading response header from upstream, client: 10.11.201.82, server: 10.11.201.82, request: "GET /socket.io/?EIO=3&transport=polling&t=1517736346555-72&sid=933777c0ced64dc4a459b1ebe33a0d21 HTTP/1.1", upstream: "http://10.11.201.82:5000/socket.io/?EIO=3&transport=polling&t=1517736346555-72&sid=933777c0ced64dc4a459b1ebe33a0d21", host: "10.11.201.82", referrer: "http://10.11.201.82/"
    2018/02/04 15:25:56 [error] 23560#23560: *83 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 10.11.201.82, server: 10.11.201.82, request: "POST /socket.io/?EIO=3&transport=polling&t=1517736356497-73&sid=933777c0ced64dc4a459b1ebe33a0d21 HTTP/1.1", upstream: "http://10.11.201.82:5000/socket.io/?EIO=3&transport=polling&t=1517736356497-73&sid=933777c0ced64dc4a459b1ebe33a0d21", host: "10.11.201.82", referrer: "http://10.11.201.82/
    
    question 
    opened by Rakin061 42
  • heroku issues

    heroku issues

    Miguel I've tried launching your example on folder and uploaded it up to heroku. here https://test-socketz.herokuapp.com/

    I changed this line 13 on the index.html

    var socket = io.connect('https://' + document.domain + ':' + location.port + namespace); from http to https since heroku complains if it's only on http

    besides that I did not change anything. the app will keep disconnecting and reconnecting and clicking echo will sometimes work and sometimes not work.

    question 
    opened by halcyonjuly7 42
  • A lot of disconnects but no reconnects

    A lot of disconnects but no reconnects

    I just got weird behaviour, after which server broke down, but that might not be the reason...

    Anyway, this looks weird:

    2018-04-07 19:55:10.029414 :: DEBUG :: dashlogger :: unknown :: Disconnect event
    2018-04-07 19:55:10.032317 :: DEBUG :: dashlogger :: unknown :: m4_30902513941193/m4_30902513941193
    2018-04-07 19:55:10.032526 :: DEBUG :: dashlogger :: unknown :: m4_30902513941193 None
    2018-04-07 19:55:10.061720 :: DEBUG :: dashlogger :: unknown :: Disconnect event
    2018-04-07 19:55:10.064122 :: DEBUG :: dashlogger :: unknown :: m4_30902513941193/m4_30902513941193
    2018-04-07 19:55:10.064372 :: DEBUG :: dashlogger :: unknown :: m4_30902513941193 None
    2018-04-07 19:55:10.094230 :: DEBUG :: dashlogger :: unknown :: Disconnect event
    2018-04-07 19:55:10.096855 :: DEBUG :: dashlogger :: unknown :: m4_30902513941193/m4_30902513941193
    2018-04-07 19:55:10.097039 :: DEBUG :: dashlogger :: unknown :: m4_30902513941193 None
    2018-04-07 19:55:10.154927 :: DEBUG :: dashlogger :: unknown :: Disconnect event
    2018-04-07 19:55:10.157444 :: DEBUG :: dashlogger :: unknown :: m4_30902513941193/m4_30902513941193
    2018-04-07 19:55:10.157622 :: DEBUG :: dashlogger :: unknown :: m4_30902513941193 None
    2018-04-07 19:55:10.342673 :: DEBUG :: dashlogger :: unknown :: Disconnect event
    2018-04-07 19:55:10.345215 :: DEBUG :: dashlogger :: unknown :: m4_30902513941193/m4_30902513941193
    2018-04-07 19:55:10.345395 :: DEBUG :: dashlogger :: unknown :: m4_30902513941193 None 
    

    And it goes on for a few seconds. And not just for this client, but others as well. It just keeps disconnecting without connection events, and within milliseconds, I'm frustrated :D

    Granted, there was some work going on with those clients, but there's no physical way to reconnect within 0.01 ms and lose connection again...

    opened by Nixellion 41
  • failed: WebSocket is closed before the connection is established.

    failed: WebSocket is closed before the connection is established.

    I'm having trouble using socket io on one of my server machines. On my server side python code logging info, it shows that the server is emitting messages to the client, but on the client side, the client doesn't seem to receive anything. and it shows the error "failed: WebSocket is closed before the connection is established." in the console followed by a series of "400 (BAD REQUEST)". It also returns "failed: Error during WebSocket handshake: Unexpected response code: 400" sometimes

    I tried on my own machine and it only works when I refresh the page (the client page does not receive anything if I close it and open it again, but it does if I refresh it again).

    question 
    opened by BoYanSTKO 41
  • Model arguments to socketio.run() on those of app.run()

    Model arguments to socketio.run() on those of app.run()

    Before Flask-WebSocketIO, I was able to start Flask like so:

    app.run(
        debug=os.environ.get('FLASK_DEBUG'),
        host=os.environ.get('FLASK_RUN_HOST'),
        port=os.environ.get('FLASK_RUN_PORT'),
        ssl_context=(
            os.environ.get('FLASK_RUN_CERT'),
            os.environ.get('FLASK_RUN_KEY'),
        )
    )
    

    With Flask-WebSocketIO, I have to start it like so:

    socketio.run(
        app,
        debug=os.environ.get('FLASK_DEBUG'),
        host=os.environ.get('FLASK_RUN_HOST'),
        port=int(os.environ.get('FLASK_RUN_PORT')),
        certfile=os.environ.get('FLASK_RUN_CERT'),
        keyfile=os.environ.get('FLASK_RUN_KEY'),
    )
    

    Mind int(), and ssl_context dropped in favor of certfile/keyfile.

    • Without int(), I'd get: TypeError: 'str' object cannot be interpreted as an integer.
    • With ssl_context, I'd end up with AttributeError: 'tuple' object has no attribute 'wrap_socket'.

    Describe the solution you'd like

    I would suggest updating the arguments to socketio.run() to accept the same as app.run() did for ease and comfort.

    question 
    opened by fabswt 1
  • make the SocketIOTestClient more conform to python-socketio for seemless substitution

    make the SocketIOTestClient more conform to python-socketio for seemless substitution

    Is your feature request related to a problem? Please describe. I'm developing a little game server based on an underlying flask-socketio and the client relies on a python-socketio client

    During unit testing, I want to provide my game client with a SocketIOTestClient instead of a socketio.Client thanks to socketio.test_client(...) Problem: the interface and life cycle is not exactly the same as python-socketio client, so I have to do many twists to get it compatible, namely on 3 points:

    • connect(...) doesn't take a url parameter
    • the mocked client is provided already connected, and subsequent calls to connect(...) are ignored, so I can't directly test my connection process
    • the mocked client doesn't have an sid provided, so can't use this as a reference in the upper layers (the fame client)

    Describe the solution you'd like

    1. add an 'url' parameter to SocketIOTestClient.connect(...) to mimic the signature from python-socketio Client.connect(...). The url can be ignored.
    2. test_client() returns a test client that claims to be not already connected, and the connection simulation happens only when connect(...) is called. 2bis. the connection simulation adds an sid attribute and set it during SocketIOTestClient.connect

    to avoid breaking compatibility with existing use of test_client(), we could even have an alternative test_unconnected_client()

    Describe alternatives you've considered

    • running a server the regular way -> since shutting it seem to be very complicated, not going there
    • create another SocketIOTestClient variant and use it on my side. Not fun

    any clarification needed? thoughts?

    question 
    opened by duquesnay 4
  • Delay in messages  a long time in socket connection

    Delay in messages a long time in socket connection

    i have a python socketio client connected to a flasksocketio server which works fine for about 4 hours , after which there is a rolling increase in delay until the messages almost trickle down , and then there is a burst of message . there are about 10 -12 messages being transmitted every second on the same connection , willing to share the code for server and client if needed . Any help is appreciated.

    Thanks and Regards!! Cheerss!!!

    question 
    opened by AniruthanV 3
  • Flask socketio breaks with new version of Werkzeug (2.1.*)

    Flask socketio breaks with new version of Werkzeug (2.1.*)

    Describe the bug Flask socketio breaks with new version of Werkzeug (2.1.*) https://github.com/pallets/werkzeug/pull/2276 This is the exception:

    from flask_socketio import disconnect
    File "/usr/local/lib/python3.8/site-packages/flask_socketio/__init__.py", line 24, in <module>
    from werkzeug.serving import run_with_reloader
    ImportError: cannot import name 'run_with_reloader' from 'werkzeug.serving' (/usr/local/lib/python3.8/site-packages/werkzeug/serving.py)
    

    From the code, it seems that the library is using the function run_with_reloader, however it is a private function that was deprecated. image

    To Reproduce Steps to reproduce the behavior:

    1. Install fresh flask socketio with werkzeug (2.1.*)
    2. Import flask socketio
    3. See error

    Expected behavior The library should not use the private function

    question 
    opened by yogevyuval 4
  • Clean shutdown for werkzeug

    Clean shutdown for werkzeug

    I have a (sightly unusual use case) running well. It needs to be a threaded application - but it's single user local interface for another project. I start the server using start_background_task() in which I run flask_SocketIO.SocketIO.run(app). I shutdown the server by sending an event which calls flask_SocketIO.SocketIO.stop(). This all works cleanly at exit.

    However I learned from the debug logs, stop() looks for werkzeug's shutdown method - which is deprecated. Will the threaded / werkzeug shutdown mechanism be updated?

    question 
    opened by georgeharker 3
Owner
Miguel Grinberg
Miguel Grinberg
Flask Sitemapper is a small Python 3 package that generates XML sitemaps for Flask applications.

Flask Sitemapper Flask Sitemapper is a small Python 3 package that generates XML sitemaps for Flask applications. This allows you to create a nice and

null 6 Jan 6, 2023
flask-apispec MIT flask-apispec (🥉24 · ⭐ 520) - Build and document REST APIs with Flask and apispec. MIT

flask-apispec flask-apispec is a lightweight tool for building REST APIs in Flask. flask-apispec uses webargs for request parsing, marshmallow for res

Joshua Carp 617 Dec 30, 2022
flask extension for integration with the awesome pydantic package

Flask-Pydantic Flask extension for integration of the awesome pydantic package with Flask. Installation python3 -m pip install Flask-Pydantic Basics v

null 249 Jan 6, 2023
Flask webassets integration.

Integrates the webassets library with Flask, adding support for merging, minifying and compiling CSS and Javascript files. Documentation: https://flas

Michael Elsdörfer 433 Dec 29, 2022
SQLAlchemy database migrations for Flask applications using Alembic

Flask-Migrate Flask-Migrate is an extension that handles SQLAlchemy database migrations for Flask applications using Alembic. The database operations

Miguel Grinberg 2.2k Dec 28, 2022
Quick and simple security for Flask applications

Note This project is non maintained anymore. Consider the Flask-Security-Too project as an alternative. Flask-Security It quickly adds security featur

Matt Wright 1.6k Dec 19, 2022
Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application.

Flask-Bcrypt Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application. Due to the recent increased prevelance of

Max Countryman 310 Dec 14, 2022
Flask-Rebar combines flask, marshmallow, and swagger for robust REST services.

Flask-Rebar Flask-Rebar combines flask, marshmallow, and swagger for robust REST services. Features Request and Response Validation - Flask-Rebar reli

PlanGrid 223 Dec 19, 2022
Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application.

Flask-Bcrypt Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application. Due to the recent increased prevelance of

Max Countryman 282 Feb 11, 2021
Flask-Starter is a boilerplate starter template designed to help you quickstart your Flask web application development.

Flask-Starter Flask-Starter is a boilerplate starter template designed to help you quickstart your Flask web application development. It has all the r

Kundan Singh 259 Dec 26, 2022
Brandnew-flask is a CLI tool used to generate a powerful and mordern flask-app that supports the production environment.

Brandnew-flask is still in the initial stage and needs to be updated and improved continuously. Everyone is welcome to maintain and improve this CLI.

brandonye 4 Jul 17, 2022
Flask Project Template A full feature Flask project template.

Flask Project Template A full feature Flask project template. See also Python-Project-Template for a lean, low dependency Python app. HOW TO USE THIS

Bruno Rocha 96 Dec 23, 2022
A Fast API style support for Flask. Gives you MyPy types with the flexibility of flask

Flask-Fastx Flask-Fastx is a Fast API style support for Flask. It Gives you MyPy types with the flexibility of flask. Compatibility Flask-Fastx requir

Tactful.ai 18 Nov 26, 2022
Flask-app scaffold, generate flask restful backend

Flask-app scaffold, generate flask restful backend

jacksmile 1 Nov 24, 2021
Flask pre-setup architecture. This can be used in any flask project for a faster and better project code structure.

Flask pre-setup architecture. This can be used in any flask project for a faster and better project code structure. All the required libraries are already installed easily to use in any big project.

Ajay kumar sharma 5 Jun 14, 2022
flask-reactize is a boostrap to serve any React JS application via a Python back-end, using Flask as web framework.

flask-reactize Purpose Developing a ReactJS application requires to use nodejs as back end server. What if you want to consume external APIs: how are

Julien Chomarat 4 Jan 11, 2022
Pf-flask-rest-com - Flask REST API Common Implementation by Problem Fighter Library

In the name of God, the Most Gracious, the Most Merciful. PF-Flask-Rest-Com Docu

Problem Fighter 3 Jan 15, 2022
Flask-Discord-Bot-Dashboard - A simple discord Bot dashboard created in Flask Python

Flask-Discord-Bot-Dashboard A simple discord Bot dashboard created in Flask Pyth

Ethan 8 Dec 22, 2022
Open-source Flask Sample built on top of flask-dance library

Open-source Flask Sample built on top of flask-dance library. The project implements the social login for Github and Twitter - Originally coded by TestDriven.IO.

App Generator 4 Jul 26, 2022