5

I have a flask application which uses application factory, and I can run gunicorn as gunicorn "run:create_app()" and this work fine.

However, I want to run it from it's parent directory, something like gunicorn "application.run:create_app" or gunicorn "application/run:create_app"

How to do this without --chdir?

Jibin Mathew
  • 4,816
  • 4
  • 40
  • 68

1 Answers1

7

You already listed the pattern that should work- that argument is a full dotted path to a python module, plus a variable from that module that is an app object. So if we had a file parent_dir/myproject/uwsgi.py with the contents

from application import create_app
app = create_app()

we could run gunicorn like

# From myproject
gunicorn uwsgi:app
# from parent_dir
gunicorn myproject.uwsgi:app

Now, the problem I suspect you are seeing, is that dotted path notation requires the parent directory to be a python package- which means you need to have an __init__.py file in myproject. Otherwise the interpreter will not look inside that folder for python files to make them importable.

Python will look inside any directory that is on its PYTHONPATH. From there, any modules will be top level, and any directories with an __init__.py file will be packages. The default behavior is to add the current directory to the PYTHONPATH variable. So with the following structure

foldera
    packagea
        __init__.py
        modulea.py
folderb
    packageb
        __init__.py
        moduleb.py
folderc
    packagec
         modulec.py

From foldera you could do import packagea.modulea but not import packageb.moduleb. from the folder packagea you could do import modulea but not import packagea.modulea (the package isn't on the path!). From folderc you couldn't import ANY of these modules- there aren't any packages or modules on the PYTHONPATH. If you did set export PYTHONPATH=foldera:folderb:folderc:$PYTHONPATH, you could import packagea.modulea AND packageb.moduleb. You still couldn't import modulec or modulea or moduleb without the full dotted path.

Paul Becotte
  • 9,767
  • 3
  • 34
  • 42