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!
Related
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
I'm trying to set-up an application which will receive HTTP GET's and POST's using python and flask-restful. The problem that I'm getting is that when I start the application I see that there are two instances of a queue being generated. I would like you to help me understand why?
Application output (terminal):
<queue.Queue object at 0x10876fdd8>
* 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: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
<queue.Queue object at 0x10ce48be0>
* Debugger is active!
* Debugger PIN: 292-311-362
Python code (ran with the following command python -m main):
import json
from flask import Flask, request
from flask_restful import Resource, Api, reqparse
import requests
import os
import threading
import queue
import sys
app = Flask(__name__)
api = Api(app)
parser = reqparse.RequestParser()
parser.add_argument("endpoint")
queue = queue.Queue()
base_path = os.path.dirname(os.path.realpath(__file__))
config = Json_Parser().get_json_object(base_path + "path")
consumer = Consumer(config, queue)
t1 = threading.Thread(target=consumer.consume)
t1.start()
class Interaction(Resource):
def get(self):
self.create_interaction()
thread_queue = consumer.get_queue()
output = thread_queue.get()
return output
api.add_resource(Interaction, '/interaction')
if __name__ == '__main__':
print(queue)
app.run(debug=True)
With the help of #Richar de Wit I changed the following line:
app.run(debug=True)
to:
app.run(debug=True, use_reloader=False)
to prevent the debugger to instantiate two queues thus giving issues later on.
The problem is referenced in this question:
Why does running the Flask dev server run itself twice?
The code below works on localhost. I get the message '50' which is the number of rows I have. But it doesn't work when I push it to heroku. I get the "Application error message" and the heroku logs just say app crashed.
And yes, the heroku app has the mongolab add-on connected.
What am I doing incorrectly?
import os
from flask import Flask
from flask.ext.pymongo import PyMongo
app = Flask(__name__)
app.debug = True
app.config['MONGO_URI'] = os.environ['MONGOLAB_URI']
mongo = PyMongo(app, config_prefix='MONGO')
#app.route("/")
def hello():
num = mongo.db.test.count()
return '%s' % num
if __name__ == "__main__":
app.run()
On heroku (unless you've changed it) mongolab stores its URI at MONGOLAB_URI (per these docs).
The crash is probably PyMongo saying it can't connect to NULL, but you can check that with heroku logs on the cli.
Check that you PyMongo version is compatible with Mongo 3.0. MongoLab has switched to it recently: http://blog.mongolab.com/2015/07/mongodb-version-3-0-now-ga-on-mongolab/
I have a python app developed on Flask. Everything works fine offline, I tried deploying on CherryPy successfully too. Now, I'm trying to deploy the same on www.pythonanywhere.com.
Here's the deploy.py I use for deploying the Flask app on CherryPy
from cherrypy import wsgiserver
from appname import app
def initiate():
app_list = wsgiserver.WSGIPathInfoDispatcher({'/appname': app})
server = wsgiserver.CherryPyWSGIServer( ('http://username.pythonanywhere.com/'), app_list)
try:
server.start()
except KeyboardInterrupt:
server.stop()
print "Server initiated..."
initiate()
print "Ended"
I created a "manual configuration" app on pythonanywhere.com.
Here's the configuration file (username_pythonanywhere_com_wsgi.py):
import sys
path = '/home/username/appname'
if path not in sys.path:
sys.path.append(path)
import deploy
deploy.initiate()
Now I'm pretty sure that it "almost worked", because in the server logs I could see my "Server initiated..." message.
2013-09-27 09:57:16 +0000 username.pythonanywhere.com - *** Operational MODE: single process ***
Server initiated...
Now the problem, when I try to view my app username.pyhtonanywhere.com/about, it times out.
This I believe is caused due to incorrect port given while starting the CherryPy server (in deploy.py).
Could anyone please tell how I can properly initiate the CherryPy server?
Joe Doherty is right. You want something more like this in you wsgi file:
import sys
sys.path = [ <path to your web app> ] + sys.path
from cherrypy._cpwsgi import CPWSGIApp
from cherrypy._cptree import Application
from <your_web_app> import <your web app class>
config_path = '<path to your cherrypy config>'
application = CPWSGIApp(
Application(<your web app class>(), '', config = config_path)
I stuck everything that should be based on your particular app in <>s.
I get the below error when I try and start Flask using uWSGI.
Here is how I start:
> # cd ..
> root#localhost:# uwsgi --socket 127.0.0.1:6000 --file /path/to/folder/run.py --callable app - -processes 2
Here is my directory structure:
-/path/to/folder/run.py
-|app
-|__init__.py
-|views.py
-|templates
-|static
Contents of /path/to/folder/run.py
if __name__ == '__main__':
from app import app
#app.run(debug = True)
app.run()
Contents of /path/to/folder/app/__init__.py
import os
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
#from flaskext.babel import Babel
from config import basedir
app = Flask(__name__)
app.config.from_object('config')
#app.config.from_pyfile('babel.cfg')
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.setup_app(app)
login_manager.login_view = 'login'
login_manager.login_message = u"Please log in to access this page."
from app import views
*** Operational MODE: preforking ***
unable to find "application" callable in file /path/to/folder/run.py
unable to load app 0 (mountpoint='') (callable not found or import error)
*** no app loaded. going in full dynamic mode ***
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI worker 1 (pid: 26972, cores: 1)
spawned uWSGI worker 2 (pid: 26973, cores: 1)
I had problems with the accepted solution because my flask app was in a variable called app. You can solve that with putting just this in your wsgi:
from module_with_your_flask_app import app as application
So the problem was simply that uwsgi expects a variable called application.
uWSGI doesn't load your app as __main__, so it never will find the app (since that only gets loaded when the app is run as name __main__). Thus, you need to import it outside of the if __name__ == "__main__": block.
Really simple change:
from app import app as application # for example, should be app
if __name__ == "__main__":
application.run()
Now you can run the app directly with python run.py or run it through uWSGI the way you have it.
NOTE: if you set --callable myapp, you'd need to change it from as application to myapp (by default uwsgi expects application
The uWSGI error unable to load app 0 (mountpoint='') (callable not found or import error) occured for me if I left out the last two lines of the following minimal working example for Flask application
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello world!"
if __name__ == "__main__":
app.run()
else:
application = app
I am aware that this already implicitly said within the comments to another answer, but it still took me a while to figure that out, so I hope to save others' time.
In the case of a pure Python Dash application, I can offer the following minimal viable code snippet:
import dash
import dash_core_components as dcc
import dash_html_components as html
app = dash.Dash()
app.layout = html.Div( html.H1(children="Hello World") )
application = app.server
if __name__ == "__main__":
app.run_server(debug=True)
Again, the application = app.server is the essential part here.