I am trying to setup config classes for my project but I can't seem to figure out how to import them properly.
Project structure:
-project
-instance
-config.py
-service
-__init__.py
config.py
:
class DefaultConfig(object):
DEBUG = True
class ProductionConfig(DefaultConfig):
DEBUG = False
__init__.py
:
from flask import Flask
def create_app():
app = Flask(__name__, instance_relative_config=True)
app.config.from_object('config.ProductionConfig')
return app
To run the app I did:
set FLASK_APP=service
set FLASK_ENV=production
FLASK run
While standing in the project
folder
That gives me this error:
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:
ModuleNotFoundError: No module named 'config'
My guess is that the path is not right. I followed this example, where they talk about using inheritance for configuration and instance folders. It made a lot of sense when I read it but I must have managed to misinterpret an integral part.
EDIT: Now it works. Instead of just
app.config.from_object('config.DefaultConfig')
I had to do
app.config.from_object('instance.config.DefaultConfig')
I think that is really confusing because setting the instance_relative_config
to True
like I did, should according to the docs set the path for the config files relative to the instance directory. Now I am accessing them relative to the project root...
After import, only the class needs to be given as a parameter.
from project.instance.config import ProductionConfig
app.config.from_object(ProductionConfig)