Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't load Flask config from parent directory

Tags:

python

flask

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?

like image 277
Juicy Avatar asked Aug 25 '16 10:08

Juicy


1 Answers

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')
like image 109
davidism Avatar answered Oct 08 '22 16:10

davidism