Flask-socketio: Flask apps not using Flask-SocketIO get exception/ValueError

Created on 15 Oct 2018  路  20Comments  路  Source: miguelgrinberg/Flask-SocketIO

Flask apps without use of Flask-SocketIO seem to get a ValueError after just typing flask run in terminal.

Example application code:

import os

from flask import Flask

app = Flask(__name__)
app.config["SECRET_KEY"] = 'secret!'

@app.route("/")
def index():
    print('hello world')
    return 'hello!'

if __name__ == '__main__':
    app.run(debug=True)

Terminal log:

flask run
 * Serving Flask-SocketIO app "application.py"
 * Forcing debug mode on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 289-305-673
Exception in thread Thread-1:
Traceback (most recent call last):
  File "c:\users\daniel\appdata\local\programs\python\python37-32\lib\threading.py", line 917, in _bootstrap_inner
    self.run()
  File "c:\users\daniel\appdata\local\programs\python\python37-32\lib\threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages\flask_socketio\cli.py", line 59, in run_server
    return run_command()
  File "c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages\click\core.py", line 722, in __call__
    return self.main(*args, **kwargs)
  File "c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages\click\core.py", line 697, in main
    rv = self.invoke(ctx)
  File "c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages\click\core.py", line 895, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages\click\core.py", line 535, in invoke
    return callback(*args, **kwargs)
  File "c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages\click\decorators.py", line 64, in new_func
    return ctx.invoke(f, obj, *args[1:], **kwargs)
  File "c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages\click\core.py", line 535, in invoke
    return callback(*args, **kwargs)
  File "c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages\flask\cli.py", line 771, in run_command
    threaded=with_threads, ssl_context=cert)
  File "c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages\werkzeug\serving.py", line 812, in run_simple
    reloader_type)
  File "c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages\werkzeug\_reloader.py", line 267, in run_with_reloader
    signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))
  File "c:\users\daniel\appdata\local\programs\python\python37-32\lib\signal.py", line 47, in signal
    handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler))
ValueError: signal only works in main thread

It seems like with Flask-SocketIO installed, a Flask-SocketIO app is always being run even if the application doesn't import Flask-SocketIO. So this issue doesn't occur with flask run with Flask-SocketIO applications, but now occurs with all other Flask applications I've written without Flask-SocketIO. I'm not sure if this is an issue with Flask or Flask-SocketIO.

The one workaround I have is to just type python application.py in command line. Any other suggestions for running the non-SocketIO applications would be appreciated. Thanks!

bug

Most helpful comment

@dcsan you can use debug mode to enable the reloader:

if __name__ == "__main__":
    socketio.run(app, debug=True)

All 20 comments

I believe this was fixed a while ago. Are you using the latest versions of Flask, Flask-SocketIO and all of its dependencies?

I believe all of the relevant packages are up to date:

Package          Version
---------------- ---------
eventlet         0.24.1
Flask            1.0.2
Flask-Session    0.3.1
Flask-SocketIO   3.0.2
gevent           1.3.7
gevent-websocket 0.10.1
Werkzeug         0.14.1

Let me know what other packages to check for version update and compatibility.

The list is incomplete. Run pip install --upgrade flask-socketio to get all the latest and report back if there are still issues.

Update command reveals that all requirements are up-to-date, but I still get the same error.

Requirement already up-to-date: Flask-SocketIO in c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages (3.0.2)
Requirement already satisfied, skipping upgrade: python-socketio>=1.6.1 in c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages (from Flask-SocketIO) (2.0.0)
Requirement already satisfied, skipping upgrade: Flask>=0.9 in c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages (from Flask-SocketIO) (1.0.2)
Requirement already satisfied, skipping upgrade: six>=1.9.0 in c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages (from python-socketio>=1.6.1->Flask-SocketIO) (1.11.0)
Requirement already satisfied, skipping upgrade: python-engineio>=2.2.0 in c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages (from python-socketio>=1.6.1->Flask-SocketIO) (2.2.0)
Requirement already satisfied, skipping upgrade: Werkzeug>=0.14 in c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages (from Flask>=0.9->Flask-SocketIO) (0.14.1)
Requirement already satisfied, skipping upgrade: itsdangerous>=0.24 in c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages (from Flask>=0.9->Flask-SocketIO) (0.24)
Requirement already satisfied, skipping upgrade: click>=5.1 in c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages (from Flask>=0.9->Flask-SocketIO) (7.0)
Requirement already satisfied, skipping upgrade: Jinja2>=2.10 in c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages (from Flask>=0.9->Flask-SocketIO) (2.10)
Requirement already satisfied, skipping upgrade: MarkupSafe>=0.23 in c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages (from Jinja2>=2.10->Flask>=0.9->Flask-SocketIO) (1.0)

Did you run pip install --upgrade flask-socketio as I suggested? You are showing me the versions that you have, and they are not the latest.

The lines from my last comment were displayed after running pip install --upgrade flask-socketio. I assumed this would show you the versions of all relevant packages and would be up to date. Sorry for the confusion.

However, after checking pip list --outdated I did find that python-engineio was outdated. Here is what I now see after upgrading all outdated packages. Running pip install --upgrade flask-socketio now shows the following:

位 pip install --upgrade flask-socketio
Requirement already up-to-date: flask-socketio in c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages (3.0.2)
Requirement already satisfied, skipping upgrade: Flask>=0.9 in c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages (from flask-socketio) (1.0.2)
Requirement already satisfied, skipping upgrade: python-socketio>=1.6.1 in c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages (from flask-socketio) (2.0.0)
Requirement already satisfied, skipping upgrade: itsdangerous>=0.24 in c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages (from Flask>=0.9->flask-socketio) (0.24)
Requirement already satisfied, skipping upgrade: Werkzeug>=0.14 in c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages (from Flask>=0.9->flask-socketio) (0.14.1)
Requirement already satisfied, skipping upgrade: click>=5.1 in c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages (from Flask>=0.9->flask-socketio) (7.0)
Requirement already satisfied, skipping upgrade: Jinja2>=2.10 in c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages (from Flask>=0.9->flask-socketio) (2.10)
Requirement already satisfied, skipping upgrade: six>=1.9.0 in c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages (from python-socketio>=1.6.1->flask-socketio) (1.11.0)
Requirement already satisfied, skipping upgrade: python-engineio>=2.2.0 in c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages (from python-socketio>=1.6.1->flask-socketio) (2.3.2)
Requirement already satisfied, skipping upgrade: MarkupSafe>=0.23 in c:\users\daniel\appdata\local\programs\python\python37-32\lib\site-packages (from Jinja2>=2.10->Flask>=0.9->flask-socketio) (1.0)

However, I still get the error. Is there something else that's outdated?

Just to make sure, here is my full pip list

Package          Version
---------------- ----------
certifi          2018.10.15
cffi             1.11.5
chardet          3.0.4
Click            7.0
Django           2.1.2
dnspython        1.15.0
eventlet         0.24.1
Flask            1.0.2
Flask-Session    0.3.1
Flask-SocketIO   3.0.2
gevent           1.3.7
gevent-websocket 0.10.1
greenlet         0.4.15
idna             2.7
itsdangerous     0.24
Jinja2           2.10
MarkupSafe       1.0
monotonic        1.5
pip              18.1
psycopg2         2.7.5
pycparser        2.19
python-engineio  2.3.2
python-socketio  2.0.0
pytz             2018.5
requests         2.20.0
setuptools       40.4.3
six              1.11.0
SQLAlchemy       1.2.12
urllib3          1.24
Werkzeug         0.14.1

Okay, so this is actually an issue that I fixed, but later it was found that the fix caused another problem. I forgot that about a month ago I undid the fix to prevent the second problem, which was more severe.

So basically, the workaround at this time is to not install Flask-SocketIO unless you use it in your application. I need to find a way for Flask-SocketIO to transparently defer to Flask when it isn't used. This worked fine with Flask pre-1.0, but with current releases it has proven tricky.

Starting with Flask-SocketIO 3.2.0 (just released), the flask run command can only be used with the threading mode. For all other async modes, the socketio.run(app) method should be used to start the server.

Just run into this problem. My demo code in #880 would raise this error even with

FLASK_ENV=development FLASK_APP=app.py flask run --with-threads

python 3.7.2, Flask 1.0.2, Flask-SocketIO 3.2.0

@gwh-cpnet what is the problem? The changes to flask run are done intentionally, if you want to use release 3.2.0 with any server other than Werkzeug you have to launch the server through socketio.run(), the flask run command is not supported anymore.

I mean the ValueError: signal only works in main thread error.

import eventlet
eventlet.monkey_patch()

from flask import Flask
from flask_socketio import SocketIO, emit

def create_app():
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret!'
    socketio = SocketIO(app)

    @socketio.on('connect')
    def connect():
        emit('notify', 'Connected')

    @socketio.on('disconnect')
    def disconnect():
        print('Client disconnected')

    return app

okay, with the demo code above saved as app.py, run with LASK_ENV=development FLASK_APP=app.py flask run, no matter whether there is --with-threads flag or not. I would get ValueError: signal only works in main thread Error.

pip list result:

Package         Version
--------------- -------
Click           7.0    
dnspython       1.16.0 
eventlet        0.24.1 
Flask           1.0.2  
Flask-SocketIO  3.2.0  
greenlet        0.4.15 
itsdangerous    1.1.0  
Jinja2          2.10   
MarkupSafe      1.1.0  
monotonic       1.5    
pip             19.0.1 
python-engineio 3.3.0  
python-socketio 3.1.1  
setuptools      40.6.2 
six             1.12.0 
Werkzeug        0.14.1 

screenshot_2019-01-24_18-50-45

As I said above, flask run only works with Werkzeug in 3.2.0. I have removed all the special handling to make flask run work with eventlet and gevent. If you want to use eventlet, run the server with socketio.run(app).

oh sorry and thanks for your explanation. I just caught up with you. So my problem is that I am using eventlet, so the server is no longer Werkzeug. I see.

Starting with Flask-SocketIO 3.2.0 (just released), the flask run command can only be used with the threading mode. For all other async modes, the socketio.run(app) method should be used to start the server.

Hello, I work with VS Code and don't know how to make it launch with socket.run(app) ?

I'm struggling integrate flask-socketio to my current project, I always have this screen :
capture

EDIT

Seems like add --no-reload like you suggest in an other issue works.

@Senseikaii you may also want to add "gevent": true to your vscode configuration if you are using gevent or eventlet. Yes, even if you use eventlet the option is called gevent.

@miguelgrinberg I'm facing this issue even if I use "flask run --with-threads" this issue is popping up like
"builtins.ValueError
ValueError: signal only works in main thread"
But when using "flask run --no-reload" I face no issues can I continue using it or will I face any issues later point in time.

As stated in this http://flask.pocoo.org/docs/0.12/server/ document ,it says that it is much better to use flask method,I could not understand it in depth ,need help about the 2 queries.

Hey guys, I was also facing the same problem. So to summarize, if you're using socket-io, don't do flask run. First, add

if __name__ == "__main__":
    socketio.run(app)

at the end of your application. To run it just do

python3 __init__.py

Hope it helped.

is there a way to run a flask app that will hot reload when code changes? thats the main reason I'm using flask run

using normal python startup is for some reason also extremely slow on my system compared to flask run, I'm not sure if the flask method somehow does some lazy loading internally?

@dcsan you can use debug mode to enable the reloader:

if __name__ == "__main__":
    socketio.run(app, debug=True)

i am getting error with flask-socketio
app is not connecting to the server
eventlet 0.25.2
Flask 1.1.2
Flask-SocketIO 4.3.0
ipykernel 5.1.4
ipython 7.13.0
Jinja2 2.11.2
watchdog 0.10.2
Werkzeug 1.0.1
Screenshot (62)
Screenshot (61)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

EndenDragon picture EndenDragon  路  3Comments

fbussv picture fbussv  路  4Comments

lnunno picture lnunno  路  4Comments

j2logo picture j2logo  路  3Comments

piyush121 picture piyush121  路  3Comments