I am converting a flask application to Docker using uwsgi-nginx-flask-docker. I am using flask_restful to support a restful interface only.
Here are the relevant parts of my webapp.py (equivalent of main.py in the example):
#!flask/bin/python
import os, sys; sys.path.append(os.path.dirname(os.path.realpath(__file__)))
from flask import Flask, jsonify, make_response
from flask_restful import Api
from flask_cors import CORS
from actual_app.frontend import resources, useradmin, entityadmin
from flask_jwt_extended import JWTManager
import logging, logging.handlers
app = Flask(__name__, static_folder='static', static_url_path='')
app.config['CORS_HEADERS'] = 'Content-Type'
cors = CORS(app, resources={r"/api": {"origins": "http://localhost"}})
logging.basicConfig(level=logging.INFO)
app.debug = True
app.config['SECRET_KEY'] = 'app-is-cool'
app.config['JWT_ACCESS_LIFESPAN'] = {'hours': 24}
app.config['JWT_REFRESH_LIFESPAN'] = {'days': 30}
jwt = JWTManager(app)
api = Api(app)
api.add_resource(resources.Login, '/api/login', methods=['POST'])
api.add_resource(resources.Logout, '/api/logout', methods=['POST'])
api.add_resource(resources.RegisterOtp, '/api/register_otp', methods=['POST'])
...
@app.route('/', methods=['POST', 'GET'])
def index():
return "<h1>Example Limited</h1>"
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
@app.errorhandler(500)
def server_error(e):
logging.exception('An error occurred during a request. %s', e)
return "An internal error occurred", 500
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True, port=80, use_reloader=False)
I run it as docker run --name app_name -d -e URL=http://localhost -e EMAIL=Dev -e CLIENT=dev -e CACHE="1 Month" -v /datanew:/datanew -p 80:80 --rm myapp/web:v01
I have the Flask application named ‘app’ as required but get this error:
unable to find "application" callable in file /app/webapp.py
unable to load app 0 (mountpoint='') (callable not found or import error)
*** no app loaded. GAME OVER ***
Ideas on what might be wrong?
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.
Aug-23-2017, 02:32 PM
(This post was last modified: Aug-23-2017, 02:32 PM by rosettas.)
Hi
I am running askbot via uWsgi, which was working fine.
But after few thing updated (maybe uWsgi from 2.0.14 to 2.0.15), it is stopped. Please help.
The versions:
Python 2.7.13
Django (1.8.17)
uWSGI (2.0.15)
The problem from uWsgi startup log:
Error:
*** Operational MODE: single process ***
handling WSGI exception
unable to find "application" callable in file /foo/askbot1/django.wsgi
unable to load app 0 (mountpoint='') (callable not found or import error)
*** no app loaded. going in full dynamic mode ***
The uWsgi configuration:
Quote:[uwsgi]
# Django-related settings
# the base directory (full path)
chdir = /foo/askbot1
# Django’s wsgi file
wsgi-file = /foo/askbot1/django.wsgi# the virtualenv (full path)
home = /bar/.virtualenvs/askbot010# process-related settings
# master
master = true
# maximum number of worker processes
processes = 1logto = /foo/askbot1/log/askbot.log
# the socket (use the full path to be safe)
socket = /foo/askbot1/site.sock
# … with appropriate permissions — may be needed
chmod-socket = 666# clear environment on exit
vacuum = true
The django.wsgi file:
import os import sys import time import traceback import signal current_directory = os.path.dirname(__file__) parent_directory = os.path.dirname(current_directory) module_name = os.path.basename(current_directory) sys.path.append(parent_directory) sys.path.append(current_directory) os.environ['DJANGO_SETTINGS_MODULE'] = '%s.settings' % module_name from django.core.wsgi import get_wsgi_application try: application = get_wsgi_application() print 'WSGI without exception' except Exception: print 'handling WSGI exception' # Error loading applications if 'mod_wsgi' in sys.modules: traceback.print_exc() os.kill(os.getpid(), signal.SIGINT) time.sleep(2.5)
Posts: 3,458
Threads: 101
Joined: Sep 2016
Reputation:
143
(Aug-23-2017, 02:32 PM)rosettas Wrote:
Error:
*** Operational MODE: single process *** handling WSGI exception unable to find "application" callable in file /foo/askbot1/django.wsgi
Quote:
from django.core.wsgi import get_wsgi_application try: application = get_wsgi_application() print 'WSGI without exception' except Exception: print 'handling WSGI exception'
wsgi works by looking for a callable object that’s specifically named «application». The error is telling you that it can’t find that variable name. And yet, you clearly are defining it.
django.core.wsgi is not complicated:
https://github.com/django/django/blob/ma…re/wsgi.py Wrote:
import django from django.core.handlers.wsgi import WSGIHandler def get_wsgi_application(): """ The public interface to Django's WSGI support. Return a WSGI callable. Avoids making django.core.handlers.WSGIHandler a public API, in case the internal WSGI implementation changes or moves in the future. """ django.setup(set_prefix=False) return WSGIHandler()
Try replacing your error handling to print out the raw error:
except Exception as err: print(err)
Maybe we can get more info that way. I’m not sure what else to do, as everything appears to be setup correctly, and the error doesn’t make sense with the file you’ve shared.
Posts: 2
Threads: 1
Joined: Aug 2017
Reputation:
0
Thanks! It works.
The raw error printing shows one postgresql lib lost. I have reinstalled the postgresql client, the problem solved.
Posts: 3,458
Threads: 101
Joined: Sep 2016
Reputation:
143
Thanks for reporting back
I get the below error when I try and start Flask using uWSGI. Here is how I start:
> # cd ..
> [email protected]:# 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)
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
if __name__ == "__main__":
app.run()
Now you can run the app directly with python run.py
or run it through uWSGI the way you have it.