I'm using flask-socketio to send data between a python web server and a client web page.
Server Code :
from flask import Flask, render_template, send_from_directory
from flask_socketio import SocketIO,emit
app=Flask(__name__, static_url_path='', static_folder="static/")
socketio=SocketIO(app)
#socketio.on('connect')
def test_connect():
print("socket connected")
if __name__=='__main__':
socketio.run(app)
Javascript client code :
const socket=io('http://localhost:5000');
socket.on('connect',()=>{
console.log('connected!');
}
Now,when I run it locally on my computer,it works fine.
But when I deployed it on Glitch and ran it, It gave me few warnings as :
Serving Flask app (lazy loading)
Environment: production
WARNING: Do not use the development server in a production environment. Use a production WSGI server instead.
Debug mode: on
Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Restarting with stat WebSocket transport not available. Install eventlet or gevent and gevent-websocket for improved performance.
Debugger is active!
Debugger PIN: 327-937-508
And my code wasn't working. I was able to open index.html but the console didn't log "socket connected". Also, none of my other socket emits were working.
After going through a few stack overflow questions, I changed my server code to :
from flask import Flask, render_template, send_from_directory
from flask_socketio import SocketIO,emit
from gevent.pywsgi import WSGIServer
app=Flask(__name__, static_url_path='', static_folder="static/")
http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()
socketio=SocketIO(app)
#socketio.on('connect')
def test_connect():
print("socket connected")
if __name__=='__main__':
socketio.run(app)
This fixed the warnings but everything still doesn't work.
Any way to fix this?
Okay. So I got it working
The problem was with client side being io('http://localhost:5000') , since the client is no longer running locally.
I fixed it by changing client to io() and server to socketio.run(app,port=3000)
Related
I have a Flask application that won't run when gevent is installed.
Here is my app.py file:
from app import create_app, socketio
app = create_app()
if __name__ == '__main__':
socketio.run(app)
init.py (with create_app)
from flask_socketio import SocketIO
...
socketio = SocketIO()
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(Config)
socketio.init_app(app, cors_allowed_origins='*')
...
return app
When I run python app.py, this is what shows in terminal:
* Restarting with stat
* Debugger is active!
* Debugger PIN: 189-464-699
With this running, my application (localhost:5000/) will not load any page- it just says Internal Server Error, even if it's not a page that uses websocket. I don't see any requests in terminal as I usually would.
What I expect when I run python app.py
* Serving Flask app "app" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 335-570-116
and of course I expect to be able to load site pages.
If I uninstall gevent, I can get the expected behavior, however, I get this error:
WebSocket transport not available. Install simple-websocket for improved performance.
simple-websocket is already installed. I took this error to mean I should install gevent and gevent-websocket.
With gevent uninstalled, I can load pages, but I receive the above transport not available error in the terminal, and the site pages that use websockets have this error in the debugger: VM78:1 GET http://localhost:5000/socket.io/?EIO=4&transport=polling&t=Ne0kF52 net::ERR_CONNECTION_REFUSED
for development environment while using socketio.run(app), its better using eventlet.
I have a flask app in which I'm implementing logging into a file. The code is as follows:
from flask import request, Flask
import os
from werkzeug.utils import secure_filename
import logging
app = Flask(__name__)
logging.basicConfig(filename='fileStorage.log', level=logging.DEBUG)
print('helloworld')
When I enter >flask run I get the following response:
* Serving Flask app "PostData.py"
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
helloworld
For some reason, the text * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) Doesn't appear. It will appear, however, if I don't set the 'filename' parameter in logging.basicConfig
What am I missing here?
I am using flask socket.io configured with eventlet on a free heroku instance. According to the flask socket.io documentation: https://flask-socketio.readthedocs.io/en/latest/ running socketio.run(app) will start a webserver if eventlet is installed.
I have a local react web app attempting to establish a WebSocket connection with this app engine instance. The web app uses socket.io and initially defaults to polling HTTP requests. These requests all timeout-- I'm unable to establish a web socket connection. I'm not sure what might be causing my issue, whether it is my app engine configuration or my flask socket.io setup.
Here is my initialization code for flask socket.io:
app = Flask(__name__)
socketio = SocketIO(app)
socketio.init_app(app, cors_allowed_origins="*")
..
..
if __name__ == '__main__':
socketio.run(app, debug=True)
Here is my Procfile:
web: python3 server.py
Here is the web app code attempting to set up the connection:
import io from 'socket.io-client'
const socketURL = "<app-engine-instance-url>:5000"
const socket = io.connect(socketURL)
You mentioned Heroku, then switched to App Engine. I assume you still meant Heroku?
The application running on Heroku must honor the $PORT environment variable and put the website on that port. Try this:
socketio.run(app, port=int(os.environ.get('PORT', '5000')))
Then from your client application connect to the Heroku URL for your app.
When I try to update the __init__.py file in Flask, it doesn't show the changes in the server, but when I edit home.html it works fine.
app/__init__.py
import os
from flask import Flask, render_template
from werkzeug.contrib.fixers import ProxyFix
app = Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')
app.wsgi_app = ProxyFix(app.wsgi_app)
app.debug = bool(os.environ.get('PRODUCTION'))
if __name__ == '__main__':
app.run()
Any tips?
We solved the problem in comments but I will add solution here if someone else has a similar problem.
For development environment add debug=True argument to your app
app.run(debug=True)
If your development environment works on an application server, then you should look for autoreload option. In uWSGI there is py-auto-reload for example.
For released, stable environment you should restart your application server.
For example in uWSGI
There are several ways to make uWSGI gracefully restart.
# using kill to send the signal
kill -HUP `cat /tmp/project-master.pid`
# or the convenience option --reload
uwsgi --reload /tmp/project-master.pid
# or if uwsgi was started with touch-reload=/tmp/somefile
touch /tmp/somefile
More: http://uwsgi-docs.readthedocs.io/en/latest/Management.html#reloading-the-server
Warning: if you combine application and web server, uWSGI and Nginx for example, then restarting Nginx won't reload your application code. Focus on the application server.
I have a Flask app that runs fine on local, but when I push to Heroku I get the error message:
* Running on http://127.0.0.1:5000/
[INFO] Starting gunicorn 18.0
[ERROR] Connection in use: ('0.0.0.0', 8163)
I tried the solution in this question, where gunicorn and werkzeug were fighting with each other, but adding a __name__ == "__main__" block to my master application file (run.py) didn't solve my error.
This SO post suggested making sure my processes were all cleaned up. I did that but it still didn't work, so I actually deleted my entire heroku app and repushed and it still gives the same error.
My run.py file looks like:
#!pl_env/bin/python
from app import app
if __name__ == "__main__":
app.run(debug=True, port=33507)
# [33507 is the Flask port on Heroku]
And my Procfile is:
web: gunicorn run:app
The __init__.py file in app is:
from flask import Flask
import os
from flask.ext.login import LoginManager
app = Flask(__name__)
app.config.from_object('config')
lm = LoginManager()
lm.init_app(app)
lm.login_view = 'login'
from app import views
Views has the meaty logic of the app in it, but I don't think there's anything in there that would mess with gunicorn. Here's the views.py imports just in case:
from flask import Flask, render_template, flash, redirect
from flask.ext.login import login_required, login_user
from app import app, lm
from forms import LoginForm
I am definitely at a loss as to where to look now to figure out this connection error. Any thoughts on why it seems to think I'm already using 0.0.0.0?
Thank you
Monica
EDIT: I ran the app locally using foreman start and it worked cleanly in 0.0.0.0:5000, so I think I'm having a Heroku problem
EDIT2: I intentionally broke my view flow -- made an internal infinite reference -- and pushed it to see what would happen. I got the expected error logs, undid it, and pushed the rollback, and now it's working. I have absolutely no idea why that should work, except maybe that breaking it in an expected way flushed my gunicorn connections. If anyone has any explanations for this mystery, I would love them.
app.run(host='0.0.0.0')
might do the trick as explained here