Python Flask socketIO server not running - python

I have this simple script with a Flask webserver. When I try to run the Python script, nothing happens, it just freezes.
I have already installed eventlet but this has not fixed the issue.
from flask import Flask, render_template
from flask_socketio import SocketIO
app = Flask(__name__, static_folder="statics", template_folder="templates")
socketio = SocketIO(app)
#app.route("/")
def main():
return render_template('index.html')
#socketio.event
def connect(sid, environ):
print(sid, 'connected')
#socketio.event
def disconnect(sid):
print(sid, 'disconnected')
if __name__ == "__main__":
socketio.run(app)
How can I stop this script from freezing and make it serve the webpage?

I am not sure what you mean by 'it freezes' but if it means you don't get any output in the terminal for debugging, you can fix that by setting debug mode to true using:
socketio.run(app, debug=True)

Related

unable to host flask app on a specific ip and port

I wanted to host my flask app on a specific port but the method I am using is not working. What I did is assign the host and port properties in my socket.run(). When I go to the specified address the page doesn't load. Where did I go wrong and how can I properly host a flask app with specific ip address and port. Thanks in advance.
EDIT: when I run the app with python app.py it works but when I run it with flask run it doesn't work.
from flask import Flask, render_template, Response
from flask_socketio import SocketIO
app = Flask(__name__)
app.config['SECRET_KEY'] = 'blahBlah'
socket = SocketIO(app)
#app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
socket.run(app, host='127.0.0.1', port=7000)
As of Flask version 0.11, setting the port param will not take affect unless config variable SERVER_NAME is set and debug=True.
Your regular Flask app will be running on default (localhost:5000).
Therefore the code should look like:
from flask import Flask, render_template
from flask_socketio import SocketIO
app = Flask(__name__)
app.config['SECRET_KEY'] = 'blahBlah'
app.config['SERVER_NAME'] = '127.0.0.1:8000'
socket = SocketIO(app)
#app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
socket.run(app, debug=True)
See Flask ref for more information: flask API
Edit:
Above code example will work so forth your code is structured:
project
app.py
templates
index.html
To run the code say:
python app.py
Running the code with the flask tools (flask run) will run the app and not the SocketIO part.
The right way
The right way to run the code is to do like this:
from flask import Flask, render_template
from flask_socketio import SocketIO
def create_app():
app = Flask(__name__)
app.config.from_mapping(
SECRET_KEY='BlaBla'
)
socket = SocketIO(app)
#app.route('/')
def index():
return render_template('index.html')
return app
Then in the shell run:
export FLASK_RUN_PORT=8000
Now you can run the flask app with the flask command:
flask --app app --debug run
maybe u are hosting something else on that specific port or on that specific ip or try to replace the socket.run by app.run

Python flask app with Nginx and uWSGI gives Internal Server Error when writing it as class

I am building a API that uses flask. I am going to use uWSGI and NGINX in production. The API is working as it is, but I am trying to rebuild it to use classes. When I run it after I have build it as a class it gives me Internal Server Error.
The following files are working:
src/server.py
from flask import Flask
app = Flask(__name__)
#app.route("/ping")
def ping():
return "pong"
if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True)
src/wsgi.py
from src.server import app
if __name__ == "__main__":
app.run()
When I try to build it as class then I get Internal Server Error
src/server.py
from flask import Flask
class Main:
app = Flask(__name__)
def __init__(self):
#self.app.route("/ping")
def ping():
return "pong"
if __name__ == "__main__":
main = Main()
main.app.run(host="0.0.0.0", debug=True)
src/wsgi.py
from src.server import Main
if __name__ == "__main__":
main = Main()
main.app.run()

How to get logger.info of Flask app in Waitress in windows?

I have the flask app serving in waitress in windows, I have logger info
app = Flask(__name__)
logging.basicConfig(level=logging.ERROR)
#app.route('/run', methods=['POST'])
def RunFunction():
…………codes...……..
app.logger.info("Log 1: Starting App on Port: {}".format(LISTEN_PORT))
…………...
If I run with flask, I get the logger info
if __name__ == '__main__':
app.run(debug=True,port=8080, threaded=True,use_reloader=False)
If I use in waitress
from waitress import serve
serve(app, host='0.0.0.0', threads=WAITRESS_THREADS, port=LISTEN_PORT)
I am not getting logger info in console
I tried
app = Flask(__name__)
logger = logging.getLogger('waitress')
logger.setLevel(logging.ERROR)
and logger codes as
logger.info("Log 1: Starting App on Port: {}".format(LISTEN_PORT))
This is not working
Also I tried
from paste.translogger import TransLogger
serve(TransLogger(app, setup_console_handler=True), host='0.0.0.0', threads=WAITRESS_THREADS, port=LISTEN_PORT)
This also not working, may I know how to get the logger info in waitress

How enable/implement Multi Threading in the WSGIServer of Flask Python

I have a Flask API which servers to Web and Mobile Apps.
But sometimes on heavy load, app or websites stop quick response and displays results taking time,
I just want to enable multithreading in the flask running with WSGIServer.
def main():
"""Main entry point of the app."""
try:
http_server = WSGIServer(('0.0.0.0', 8084), app, log=logging, error_log=logging)
http_server.serve_forever()
except Exception as exc:
logger.error(exc.message)
logger.exception(traceback.format_exc())
finally:
# Do something here
pass
Thanks,
The built-in Flask development server, whilst not intended for multithreaded use or deployment does allow multithreading:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return 'Hello, world!'
if __name__ == '__main__':
app.run(threaded=True)
The above code is a simple Hello World script that uses multithreading; not that any process is using another thread, but you get the idea.

Emitting event from socketIo python

I'm stuck in development of socket.io with Python. I'm using this lib
I got a chat app running by using this android part and with the lib sample. I want to trigger an event from the server side from a separate file. Here's my code.
import socketio
import eventlet
from flask import Flask, render_template
sio = socketio.Server(logger=True, async_handlers= True)
app = Flask(__name__)
eventlet.monkey_patch()
#sio.on('connect', namespace='/d')
def connect(sid, environ):
print('connect ', sid)
pass
#sio.on('messaget', namespace='/d')
def messaget(sid, data):
print('message ', data)
# sio.emit('messaget', data, namespace='/d')
# sendmsg("YO YO")
#sio.on('disconnect', namespace='/d')
def disconnect(sid):
print('disconnect ', sid)
def start_socket(app):
# wrap Flask application with socketio's middleware
app = socketio.Middleware(sio, app)
eventlet.wsgi.server(eventlet.listen(('', 8000)), app)
def sendmsg(data):
my_data= { 'text': data };
sio.emit('messaget', my_data, namespace='/d')
start_socket(app)
I'm calling sendmsg("dipen") from my another python file. I'm getting a log emitting event "messaget" to all [/d] but android app is not getting any messages. And it work's if event is emitting from the Android app. I tried with the NodeJs code and it worked for the NodeJs code so I'm pretty sure that something is wrong in my Python code. Hope that someone could save me from this.
Send a message from Android client. Does your Python code get it? If not, check if you have connected to the same namespace.

Categories

Resources