Deploying Flask Socket.io application with eventlet on heroku - python

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.

Related

Python Flask-socketio not connecting

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)

Deploying Flask Socket.io application with eventlet on Google AppEngine

I am using flask socket.io configured with eventlet on a flexible google appengine 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 app.yaml:
runtime: python
env: flex
entrypoint: python3 server.py
runtime_config:
python_version: 3
manual_scaling:
instances: 1
network:
session_affinity: true
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)

How to access Virtualbox Python Flask service from host browser?

I have written a simple Python Flask application as follows:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello_world():
return 'Hello World2'
if __name__ == '__main__':
app.run(debug=True, port=5000)
This code is then executed in my Virtual box Ubuntu 18.04 Server VM. It starts listening to port 5000 in my VM.
However, when I try to access it from my host browser at 127.0.0.1:6000, it is not loading.
I have enabled port forwarding in Virtualbox NAT port forwarding option as shown below:
How to access the Flask server from host?
Most probably your application binds to loopback network interface.
Change it to bind to all interfaces so it is accessible from the outside:
app.run(host='0.0.0.0', debug=True, port=5000)

How to run Flask web app without using command? [duplicate]

This question already has answers here:
Are a WSGI server and HTTP server required to serve a Flask app?
(3 answers)
Closed 4 years ago.
I'm running my flask web app on local from command line using python __init__.py command. I want to run/deploy flask web without using any command. Like spring web app.
init.py
from flask import Flask, url_for
from flask import jsonify
from werkzeug.serving import run_simple
from werkzeug.wsgi import DispatcherMiddleware
import db_config
app = Flask(__name__)
app.config['APPLICATION_ROOT'] = '/my-web-app'
def simple(env, resp):
resp(b'200 OK', [(b'Content-Type', b'text/plain')])
return [b'Hello my app User']
#app.route("/")
def hello():
return "Hello world"
#app.route('/test', methods=['GET'])
def get_tasks():
db = db_config.getconnection();
cur = db.cursor()
cur.execute("SELECT * FROM emp")
items = cur.fetchall()
print(items)
db.commit()
cur.close()
db.close()
return jsonify({'tasks': items})
app.wsgi_app = DispatcherMiddleware(simple, {'/my-web-app': app.wsgi_app})
if __name__ == "__main__":
app.run()
Is there any way to create .WAR file of flask web app and deploy it on server? And start web app when we give request.
Is there any way to create a Java .WAR file from a Flask app? Possibly, but I really wouldn't recommend it. Python is not Java.
Is there any way to deploy a Flask application on a server? Oh yes, lots of ways. The Deployment Options page in the Flask documentation lists several options, including:
Hosted options: Deploy Flask on Heroku, OpenShift, Webfaction, Google App Engine, AWS Elastic Beanstalk, Azure, PythonAnywhere
Self-hosted options: Run your own server using a standalone WSGI container (Gunicorn, uWSGI, Gevent, Twisted), using Apache's mod_wsgi, using FastCGI, or using old-school vanilla CGI.
Of the self-hosted options, I would definitely recommend nginx rather than Apache as a front-end web server, and nginx has built-in support for the uWSGI protocol, which you can then use to run your app using the uwsgi command.
But I would definitely recommend looking into one of the hosted options rather than being in the business of running your own web server, especially if you're just starting out. Google App Engine and AWS Elastic Beanstalk are both good platforms to start out with as a beginner in running a cloud web application.

"Connection in use" error in GCP app engine

I am new to GCP App engine. I am trying to make web server using flask on App engine. I tested the version of my code on localhost and it is working fine. But when I am trying to deploy it in the App Engine of GCP it is giving me this strange error "app logs".
error logs
Here is my code for the flask
app.run(threaded = True, host='127.0.0.1', port=80)
Thanks!!
You don't need to call app.run() in your main.py file -- App Engine will do that for you. Simply initialize the app variable in this file instead.

Categories