unable to host flask app on a specific ip and port - python

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

Related

Deploy a flask app in using Cloudera Application

I have been using the following python 3 script in a CDSW session which run just fine as long as the session is not killed.
I am able to click on the top-right grid and select my app
hello.py
from flask import Flask
import os
app = Flask(__name__)
#app.route('/')
def index():
return 'Web App with Python Flask!'
app.run(host=os.getenv("CDSW_IP_ADDRESS"), port=int(os.getenv('CDSW_PUBLIC_PORT')))
I would like this app to run 24/7, so instead of using a Session or scheduling a job that never ends, I would like to create a CDSW Application so that it doesn't stop.
This is the settings on my application:
Logs:
from flask import Flask
import os
app = Flask(__name__)
#app.route('/')
def index():
return 'Web App with Python Flask!'
app.run(host=os.getenv("CDSW_IP_ADDRESS"), port=int(os.getenv('CDSW_PUBLIC_PORT')))
* Serving Flask app "__main__" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
OSError: [Errno 98] Address already in use
I tried to change the port from CDSW_PUBLIC_PORT to CDSW_APP_PORT but it ends up the same.
As it mentions here maybe you need to change this line of code
app.run(host=os.getenv("CDSW_IP_ADDRESS"), port=int(os.getenv('CDSW_PUBLIC_PORT')))
to this
app.run(host="127.0.0.1", port=int(os.environ['CDSW_APP_PORT']))
Hope it works!

Python Flask socketIO server not running

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)

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 to emit data from background process to Flask-SocketIO

emitted data from different process to socketio but not working
I created Flask App in which I am using Flask-SocketIO framework. The code for flask app is below:
from web import create_app, socketio
app = create_app()
if __name__ == '__main__':
socketio.run()
I am running this using flask run command.
But I have another python script in which I am importing socketio and want to emit data to client's browser.
# cli-script.py
import time
from web import socketio
def demo():
while 1:
socketio.emit('my-event', ("My Data"))
time.sleep(10)
demo()
My flask application folder structure looks like this:
/-
web
__init__.py
code.py
web-script.py
cli-script.py
and I am running two python processes:
flask run
python cli-script.py
Why this doesn't work ?

flask socketio not starting

Trying to get a flask socketio app going.
Here's my init.py
import os
from flask import Flask, logging
from flask_socketio import SocketIO
from flask_sqlalchemy import SQLAlchemy
from config import app_config
database = SQLAlchemy()
socket_io = SocketIO()
def create_app(config_name):
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(app_config[config_name])
database.init_app(app)
socket_io.init_app(app)
from .home import home as home_blueprint
app.register_blueprint(home_blueprint)
return app
and here is my run.py
#!/usr/bin/env python3
import sys
from app import create_app, socket_io
config_name = sys.argv[1]
app = create_app(config_name)
if __name__ == "__main__":
socket_io.run(app)
When I start up the app, this is the log output in the python console:
C:\AnacondaPython\python.exe D:/workspaces/App/run.py development
* Restarting with windowsapi reloader
* Debugger is active!
* Debugger PIN: 189-233-458
And then nothing happens.
When I open the app in the browser, it just keeps loading.
How do I do this correctly?
I'll provide more code if necessary.
Thanks for any help and tips!

Categories

Resources