Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

config.from_object does not work in Flask with Python 3

I have the following Flask code, file __init__.py:

from flask import Flask
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from flask_sqlalchemy_session import flask_scoped_session

from . import configmodule

app = Flask(__name__)

engine = create_engine(configmodule.DevelopmentConfig.SQLALCHEMY_DATABASE_URI)  # <--- THIS WORKS

session_factory = sessionmaker(bind=engine)
session = flask_scoped_session(session_factory, app)

app.config.from_object('configmodule.DevelopmentConfig')  # <--- THIS FAILS IN Python 3

                                 ...

The file configmodule.py is in the same directory as __init__.py above.

After I run it using python 3.5.2, I get:

werkzeug.utils.ImportStringError: import_string() failed for 'configmodule.DevelopmentConfig'. 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:

- 'configmodule' not found.

This error is for the last line in the code snippet:

app.config.from_object('configmodule.DevelopmentConfig')  # <--- THIS FAILS IN Python 3

I had no problem running it with Python 2. Any idea how to make it work with Python 3? Thanks.

like image 689
jazzblue Avatar asked Jan 04 '23 21:01

jazzblue


1 Answers

Python 3 dropped support for implicit relative imports. You'll need to use an absolute import

app.config.from_object('packagename.configmodule.DevelopmentConfig')

Explicit relative imports don't appear to be supported by from_object.

This is touched on in the imports section of PEP 8.

Edit: Removed explicit import example.

like image 132
dirn Avatar answered Jan 13 '23 11:01

dirn