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)
CodePudding user response:
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
CodePudding user response:
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