Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gunicorn failed to load Flask application

I have a Flask app I am trying to serve via Gunicorn.

I am using virtualenv and python3. If I activate my venv cd to my app base dir then run:

gunicorn mysite:app

I get:

Starting gunicorn
Listening at http://127.0.0.1:8000
DEBUG:mysite.settings:>>Config()
...
Failed to find application: 'mysite'
Worker exiting
Shutting down: master
Reason: App failed to load

Looking in /etc/nginx/sites-available I only have the file 'default'. In sites-enabled I have no file.

In my nginx.conf file I have:

include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;

App structure:

mysite    #this is where I cd to and run gunicorn mysite:app
--manage.py
--/mysite
----settings.py
----__init__.py

in manage.py for mysite I have following:

logger.debug("manage.py entry point")
app = create_app(app_name)
manager = Manager(app)

if __name__ == "__main__":
    manager.run()

In __init__.py file:

def create_app(object_name):
    app = Flask(__name__)
    #more setup here
    return app

In my settings.py in the app directory

class Config(object):
    logger.debug(">>Config()")  #this logs OK so gunicorn is at least starting in correct directory

From inside the virtualenv if I run

print(sys.path)

I find a path to python and site-packages for this virtualenv.

From what I have read to start gunicorn it's just a matter of installing it and running gunicorn mysite:app

Running gunicorn from the parent directory of mysite I get the same failed to find application: 'mysite', App failed to load error, but don't get the DEBUG...Config() logged (as we are clearly in the wrong directory to start in). Running gunicorn from mysite/mysite (clearly wrong) I get and Exception in worker process ereor, ImportError: No module named 'mysite'.

Any clues as to how I can get gunicorn running?

like image 772
Don Smythe Avatar asked Apr 01 '16 01:04

Don Smythe


1 Answers

You're pointing gunicorn at mysite:app, which is equivalent to from mysite import app. However, there is no app object in the top (__init__.py) level import of mysite. Tell gunicorn to call the factory.

gunicorn "mysite:create_app()"

You can pass arguments to the call as well.

gunicorn "mysite:create_app('production')"

Internally, this is equivalent to:

from mysite import create_app
app = create_app('production')

Alternatively, you can use a separate file that does the setup. In your case, you already initialized an app in manage.py.

gunicorn manage:app
like image 190
davidism Avatar answered Oct 17 '22 03:10

davidism