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
Python 2 or Python 3? If you Google this issue, some people reported this error with Python 2, but the problem was address in Python 3, so maybe give 3 a try if you are using 2.
Also things may change if you change your async mode. Do you currently have eventlet or gevent installed on your virtualenv? If not, try installing eventlet, that will give you the benefit of having WebSocket support, and will use a different web server, which may help bypass the issue. If you are getting this error with eventlet installed, then try gevent instead, once again, it's a different web server, so you may have better luck.
python 3.6.4 (anaconda)
i have just updated python pip to 1.81
i tried default and eventlet so far both same result
"D:\WORK\study sc5\project2\project2>flask run
"update:
i tried gevent >>> same result
but i dont know what to do should i remove anaconda and install python ?
I'm not sure. It's been a while since I've used the native version of Python on Windows, on that platform I use either the Ubuntu subsystem or Cygwin, and both seem very stable. I'll find a Windows machine to test again and let you know. As one more test you may want to try the example application in this repository, just to rule out a problem in your own application.
honstly i dont know how to use the repository
but that is all the code i have in application.py
import os
from flask import Flask
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.config["SECRET_KEY"] = "sdfsdfssefe"
socketio = SocketIO(app)
@app.route("/")
def index():
return "Project 2: TODO"
i appraciate your help alot i just wanna say that
also i have tested it with windows10 and windows 7 different machines
Okay, I'll look for a Windows machine to test this on and get back to you.
thank you so much !!
i have tried to upgrade anaconda it didnt work ( bugged for some reason ) so i closed it , uninstall it and started setting up everything and environmental variables again
now i have Anaconda Navigator 1.9.2 which suppose to be the latest version
when i tested the same code i got this extra line
D:\WORK\study sc5\project2\project2>flask run
Serving Flask-SocketIO app "application
Forcing debug mode off
i appreciate your effort sir , thanks a lot
What's the output of the pip freeze command?
alabaster==0.7.11
anaconda-client==1.7.2
anaconda-navigator==1.9.2
anaconda-project==0.8.2
appdirs==1.4.3
asn1crypto==0.24.0
astroid==2.0.4
astropy==3.0.4
atomicwrites==1.2.1
attrs==18.2.0
Automat==0.7.0
Babel==2.6.0
backcall==0.1.0
backports.shutil-get-terminal-size==1.0.0
beautifulsoup4==4.6.3
bitarray==0.8.3
bkcharts==0.2
blaze==0.11.3
bleach==2.1.4
bokeh==0.13.0
boto==2.49.0
Bottleneck==1.2.1
certifi==2018.8.24
cffi==1.11.5
chardet==3.0.4
click==6.7
cloudpickle==0.5.5
clyent==1.2.2
colorama==0.3.9
comtypes==1.1.7
conda==4.5.11
conda-build==3.15.1
constantly==15.1.0
contextlib2==0.5.5
cryptography==2.3.1
cycler==0.10.0
Cython==0.28.5
cytoolz==0.9.0.1
dask==0.19.1
datashape==0.5.4
decorator==4.3.0
defusedxml==0.5.0
distributed==1.23.1
docutils==0.14
entrypoints==0.2.3
et-xmlfile==1.0.1
fastcache==1.0.2
filelock==3.0.8
Flask==1.0.2
Flask-Cors==3.0.6
Flask-SocketIO==3.0.2
gevent==1.3.6
glob2==0.6
greenlet==0.4.15
h5py==2.8.0
heapdict==1.0.0
html5lib==1.0.1
hyperlink==18.0.0
idna==2.7
imageio==2.4.1
imagesize==1.1.0
incremental==17.5.0
ipykernel==4.10.0
ipython==6.5.0
ipython-genutils==0.2.0
ipywidgets==7.4.1
isort==4.3.4
itsdangerous==0.24
jdcal==1.4
jedi==0.12.1
Jinja2==2.10
jsonschema==2.6.0
jupyter==1.0.0
jupyter-client==5.2.3
jupyter-console==5.2.0
jupyter-core==4.4.0
jupyterlab==0.34.9
jupyterlab-launcher==0.13.1
keyring==13.2.1
kiwisolver==1.0.1
lazy-object-proxy==1.3.1
llvmlite==0.24.0
locket==0.2.0
lxml==4.2.5
MarkupSafe==1.0
matplotlib==2.2.3
mccabe==0.6.1
menuinst==1.4.14
mistune==0.8.3
mkl-fft==1.0.4
mkl-random==1.0.1
more-itertools==4.3.0
mpmath==1.0.0
msgpack==0.5.6
multipledispatch==0.6.0
navigator-updater==0.2.1
nbconvert==5.4.0
nbformat==4.4.0
networkx==2.1
nltk==3.3
nose==1.3.7
notebook==5.6.0
numba==0.39.0
numexpr==2.6.8
numpy==1.15.1
numpydoc==0.8.0
odo==0.5.1
olefile==0.46
openpyxl==2.5.6
packaging==17.1
pandas==0.23.4
pandocfilters==1.4.2
parso==0.3.1
partd==0.3.8
path.py==11.1.0
pathlib2==2.3.2
patsy==0.5.0
pep8==1.7.1
pickleshare==0.7.4
Pillow==5.2.0
pkginfo==1.4.2
pluggy==0.7.1
ply==3.11
prometheus-client==0.3.1
prompt-toolkit==1.0.15
psutil==5.4.7
py==1.6.0
pyasn1==0.4.4
pyasn1-modules==0.2.2
pycodestyle==2.4.0
pycosat==0.6.3
pycparser==2.18
pycrypto==2.6.1
pycurl==7.43.0.2
pyflakes==2.0.0
Pygments==2.2.0
pylint==2.1.1
pyodbc==4.0.24
pyOpenSSL==18.0.0
pyparsing==2.2.0
PySocks==1.6.8
pytest==3.8.0
pytest-arraydiff==0.2
pytest-astropy==0.4.0
pytest-doctestplus==0.1.3
pytest-openfiles==0.3.0
pytest-remotedata==0.3.0
python-dateutil==2.7.3
python-engineio==2.3.1
python-socketio==2.0.0
pytz==2018.5
PyWavelets==1.0.0
pywin32==223
pywinpty==0.5.4
PyYAML==3.13
pyzmq==17.1.2
QtAwesome==0.4.4
qtconsole==4.4.1
QtPy==1.5.0
requests==2.19.1
rope==0.11.0
ruamel-yaml==0.15.46
scikit-image==0.14.0
scikit-learn==0.19.2
scipy==1.1.0
seaborn==0.9.0
Send2Trash==1.5.0
service-identity==17.0.0
simplegeneric==0.8.1
singledispatch==3.4.0.3
six==1.11.0
snowballstemmer==1.2.1
sortedcollections==1.0.1
sortedcontainers==2.0.5
Sphinx==1.7.9
sphinxcontrib-websupport==1.1.0
spyder==3.3.1
spyder-kernels==0.2.6
SQLAlchemy==1.2.11
statsmodels==0.9.0
sympy==1.1.1
tables==3.4.4
tblib==1.3.2
terminado==0.8.1
testpath==0.3.1
toolz==0.9.0
tornado==5.1
tqdm==4.26.0
traitlets==4.3.2
Twisted==18.7.0
unicodecsv==0.14.1
urllib3==1.23
wcwidth==0.1.7
webencodings==0.5.1
Werkzeug==0.14.1
widgetsnbextension==3.4.1
win-inet-pton==1.0.1
win-unicode-console==0.5
wincertstore==0.2
wrapt==1.10.11
xlrd==1.1.0
XlsxWriter==1.1.0
xlwings==0.11.8
xlwt==1.3.0
zict==0.1.3
zope.interface==4.5.0
what should i do ?
As I said above, if you were willing to switch to the Ubuntu subsystem on your Windows machine, or maybe install Cygwin, then everything will work fine, because these two use a Unix build of Python.
If you prefer to stay with your current Windows native Python, then I'm not sure. This problem is mentioned a lot if you Google it. If the application works well in spite of the error, then maybe it is okay to ignore it.
i have installed Cygwin and thatis what happen when i run project 1 which have no Socket io
D:\Work\study\project1>flask run
when i ran project 2 now it shows an error ( which socketIO ):
D:\Work\study\project2org\project2>flask run
The second error means that you have some other application that was recently running on the same port. After a few minutes the port will be free and you will be able to use it. You can try using a different port number if you don't want to wait.
yea i got it i closed it the other server running on cmd and it worked
i ran it again on cmd ( project 2 behaving the same way as before ) when i run it project2 or project1 with cgywin he doesn't even see the python app
Mena@Mena-PC /cygdrive/d/work/study/project2org/project2
$ flask run
Usage: flask run [OPTIONS]
Error: Could not locate a Flask application. You did not provide the "FLASK_APP" environment variable, and a "wsgi.py" or "app.py" module was not found in the current directory.
Mena@Mena-PC /cygdrive/d/work/study/project2org/project2
The error is self-explanatory. Set the FLASK_APP environment variable.
Mena@Mena-PC /cygdrive/d/work/study/project2org/project2
$ set flask_app=application.py
Mena@Mena-PC /cygdrive/d/work/study/project2org/project2
$ flask run
Usage: flask run [OPTIONS]
Error: Could not locate a Flask application. You did not provide the "FLASK_APP" environment variable, and a "wsgi.py" or "app.py" module was not found in the current directory.
i know i already did
its just for some reason works on CMD not on cgywin
Mena@Mena-PC /cygdrive/d/work/study/project2org/project2
$ export FLASK_APP="application.py"
Mena@Mena-PC /cygdrive/d/work/study/project2org/project2
$ flask run
nothing happen for a while now ( around 1 min )
when i go to http://127.0.0.1:5000/ it reads "Project 2: TODO"
Mena@Mena-PC /cygdrive/d/work/study/project2/project2
$ export FLASK_APP="application.py"
Mena@Mena-PC /cygdrive/d/work/study/project2/project2
$ flask run
Usage: flask run [OPTIONS]
Error: Could not import "application".
should i run it on windows safe mode ??
iam so tired of trying just to get it to work :S
You seem to be having very basic set up problems, more related to Flask than Flask-SocketIO. Unfortunately I cannot help you with details, as aI do not know how your application is structured. If you have the app somewhere I can look at it I can give you some more advice, but really this should not take so much time, you have to point Flask at the application.
I should mention that in the Windows native case, you should use set FLASK_APP=..., not the lowercase flask_app.
dude literally that is all i have in the code which everyone in my course have it as well but no one with this problem :S
when it run with cgywin >>>>
Mena@Mena-PC /cygdrive/d/work/study/project2org/project2
$ export FLASK_APP="application.py"
Mena@Mena-PC /cygdrive/d/work/study/project2org/project2
$ flask run
when i try it with CMD >>>>>
D:\WORK\study sc5\project2org\project2>flask run
Serving Flask-SocketIO app "application
Forcing debug mode off
it say server is running on 127.0.0.1:5000 if the code doesnt have socket io in it , if it does it only says what i have mentioned above and yes when i visit 127.0.0.1:5000 i see it working but abslout silence if i tried to send anything from socket io
i had a different version as well , no errors at all , it prints anything related to python but none from socket io
also when i used inspector tool by chrome and checked the network tab i can see few socket io data moves but within few mins later i get this error i have mentioned above ( that was on windows 10 )
[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
here some videos from my pc to administrate what happen exactly
None of the zip files you attached on this issue are valid.
$ unzip Bandicam.zip
Archive: Bandicam.zip
End-of-central-directory signature not found. Either this file is not
a zipfile, or it constitutes one disk of a multi-part archive. In the
latter case the central directory and zipfile comment will be found on
the last disk(s) of this archive.
unzip: cannot find zipfile directory in one of Bandicam.zip or
Bandicam.zip.zip, and cannot find Bandicam.zip.ZIP, period.
it was winrar but the system doesn't allow me to upload winrar
i will try to make them in windows zip file then
here are the videos >>>>
project 2 which all students have - almost empty just have socket io in it
project 2 org.zip
The problem with app-test.py is that it is not an importable name, the dash is not a valid character for Python modules.
The other problem I said I will investigate once I have access to a Windows machine. Cygwin or the Ubuntu subsystem will (I think) not have have that problem. On the Windows version you may get it to work if you uninstall gevent (I suspect an incompatibility with gevent, but this is just a hunch).
i don't have gevent installed currently , and i have tested Cygwin , same reaction , it never prints "Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)" basically ignor anything related to socket io
Pretty sure you have either gevent or eventlet installed. The output would be different if you hadn't.
Here is another thing for you to try, in any case. Add the following at the bottom of application.py:
if __name__ == '__main__':
socketio.run(app)
Then start the application by running:
python application.py
Does that work better?
There is a bug in Flask related to the flask run command that might be causing your problem: https://github.com/pallets/flask/issues/2776.
i did that ..
it gave no output in CMD put when i ran 127.0.0.1:5000 it prints ( Project 2: TODO )
which is responding to
@app.route("/")
def index():
return "Project 2: TODO"
hey i uninstalled socketio and tried to reinstall it again i got this
C:\Windows\system32>pip install socketio
Collecting socketio
Using cached https://files.pythonhosted.org/packages/7e/c9/44c96fdea0802845ac1
a11f5c2b141c9995fb6bc88c66319faeecd3f8624/socketio-0.1.4.zip
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "c:\users\mena\appdata\local\programs\python\python37-32\lib\site-pac
kages\setuptools\__init__.py", line 12, in <module>
from setuptools.extension import Extension
File "c:\users\mena\appdata\local\programs\python\python37-32\lib\site-pac
kages\setuptools\extension.py", line 7, in <module>
from setuptools.dist import _get_unpatched
File "c:\users\mena\appdata\local\programs\python\python37-32\lib\site-pac
kages\setuptools\dist.py", line 16, in <module>
import pkg_resources
File "c:\users\mena\appdata\local\programs\python\python37-32\lib\site-pac
kages\pkg_resources.py", line 1479, in <module>
register_loader_type(importlib_bootstrap.SourceFileLoader, DefaultProvid
er)
AttributeError: module 'importlib._bootstrap' has no attribute 'SourceFileLo
ader'
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\Mena\App
Data\Local\Temp\pip-install-g0jwmvea\socketio\
It's pip install python-socketio. You installed something else.
i managed to install both socketio and eventlet
C:\Windows\system32>pip install python-socketio
Requirement already satisfied: python-socketio in c:\users\mena\appdata\local\pr
ograms\python\python37-32\lib\site-packages (2.0.0)
Requirement already satisfied: six>=1.9.0 in c:\users\mena\appdata\local\program
s\python\python37-32\lib\site-packages (from python-socketio) (1.11.0)
Requirement already satisfied: python-engineio>=2.2.0 in c:\users\mena\appdata\l
ocal\programs\python\python37-32\lib\site-packages (from python-socketio) (2.3.1
)
but when i ran the server , same thing happen
anyway i can trace where is this problem coming from ? .. any logging or anything ?
Sorry, but I am very confused. What do you mean by "same thing happen"? You already reported five or six different outcomes, how am I supposed to know which one you are referring to? Does the server work or not?
i'm sorry as i've mentioned earlier i'm googleing and trying different thing just to help us figure it out
so i tried to remove socket io and eventlet and reinstall them but i ran into a problem i thought it would share it with you maybe it happen because it might be a clue that something is conflicting with socketIo but i managed to resolve them , thanks to u and stackoverflow
now i tried to run the code after the fresh installation i got the same result
D:\Work\study\project2org\project2>flask run
* Serving Flask-SocketIO app "application.py"
* Forcing debug mode off
I believe I told you several times that I need to investigate why this happens when I have access to a Windows machine. There is nothing I can do right now. On the other side, I suggested you try something else that you apparently have ignored: https://github.com/miguelgrinberg/Flask-SocketIO/issues/807#issuecomment-428562995.
@miguelgrinberg i'm trying other things to get socket Io to work i'm not ignoring it sir.
it would help if there is a way to read loggin from my machine about socket io
Logging options are documented: https://flask-socketio.readthedocs.io/en/latest/#flask_socketio.SocketIO. This is not going to help you though, your application is hanging before the web server or Socket.IO get a chance to start.
then maybe logging for python or flask can provide us with a clue of where the smoke is coming from ?
i have the same problem, it because i install wrong package socketio, and installed dependency setuptools-3.3, that polluted my venv. just uninstall and reinstall setuptools to new version.