user1558914 user1558914 - 4 months ago 17
Python Question

py.test import error "- 'config' not found."

While trying to add py.test functionality to a Flask API I ran into the following error message when calling py.test on my source directory

E ImportStringError: import_string() failed for 'config'. Possible reasons are:
E
E - missing __init__.py in a package;
E - package or module path not included in sys.path;
E - duplicated package or module name taking precedence in sys.path;
E - missing module, class, function or variable;
E
E Debugged import:
E
E - 'config' not found.
E
E Original exception:
E
E ImportError: No module named config


The issue seems to stem after I have instantiated my Flask app and try to import the config from config.py (line 5).

from flask import Flask

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

# Import views
from views import *

if __name__ == '__main__':
app.run()


Everything seems to work accordingly if I manually set the config variables instead of importing them. Has anyone encountered anything like this? I wasn't able to find anything helpful in the documentation.

Answer

I suppose these ones are the most probable

E           - package or module path not included in sys.path;
E           - duplicated package or module name taking precedence in sys.path;

So the first thing I'd try is to rename config file to something like config_default.py.

Then you can try to use the real object instead of string eg. importing config yourself:

from flask import Flask
import config

# Setup app
app = Flask(__name__)
app.config.from_object(config)

But most likely you'll face the same error: ImportError: No module named config

Also you can use app.config.from_pyfile() and specify full path to your config file:

app.config.from_pyfile('config.py')

from_pyfile() uses different technic to create object (it uses [exc](https://github.com/mitsuhiko/flask/blob/master/flask/config.py#L129)).

I myself prefere to use from_envvar() and specify which config file to use in launcher (supervisord nowadays).

Comments