Juicy
Juicy

Reputation: 12520

Can't load Flask config from parent directory

I'm trying to follow the docs here on using configuration files: http://exploreflask.com/en/latest/configuration.html#the-simple-case

I want to use what they call "the simple case" but I want to load the config.py from the parent directory. My project tree looks like this:

~/Learning/test $ tree
.
├── app
│   └── __init__.py
└── config.py

This is my app/__init__.py:

from flask import Flask

app = Flask(__name__)
app.config.from_object('config')

This is my config.py:

DEBUG = True

This is the error I get when I try to run my project:

Traceback (most recent call last):
  File "app/__init__.py", line 4, in <module>
    app.config.from_object('config')
  File "/usr/local/lib/python2.7/dist-packages/flask/config.py", line 163, in from_object
    obj = import_string(obj)
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/utils.py", line 443, in import_string
    sys.exc_info()[2])
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/utils.py", line 418, in import_string
    __import__(import_name)
werkzeug.utils.ImportStringError: import_string() failed for 'config'. Possible reasons are:

- missing __init__.py in a package;
- package or module path not included in sys.path;
- duplicated package or module name taking precedence in sys.path;
- missing module, class, function or variable;

Debugged import:

- 'config' not found.

Original exception:

ImportError: No module named config

I want to keep the config.py in another directory from the Flask app files. How can I make Flask load the config.py from the parent directory here?

Upvotes: 12

Views: 7510

Answers (1)

davidism
davidism

Reputation: 127200

You can't load it from there because as the error message says:

- missing __init__.py in a package;
- package or module path not included in sys.path;

It's not part of a package that is importable. This may have worked locally because you were running python in your project root so the current directory was implicitly added to the path. Do not rely on this behavior. Do not manually change sys.path.

Instead, Flask's Config has alternate ways to load the config: from a path in an environment variable

export FLASK_CONFIG="/path/to/config.py"
app.config.from_envvar('FLASK_CONFIG')

or from a file relative to the instance folder

app/
    __init__.py
instance/
    config.py
app = Flask(__name__, instance_relative_config=True)
app.config.from_pyfile('config.py')

Upvotes: 11

Related Questions