Importing two modules of same name
Tim Johnson
tim at akwebsoft.com
Tue Feb 9 20:03:46 EST 2016
* Carl Meyer <carl at oddbird.net> [160209 15:28]:
> Hi Tim,
<...>
> The proper way to do this in Python 2.7 is to place `from __future__
> import absolute_import` at the top of flask/app/__init__.py (maybe best
> at the top of every Python file in your project, to keep the behavior
> consistent). Once you have that future-import, `import config` will
> always import the top-level config.py. To import the "local" config.py,
> you'd either `from . import config` or `import app.config`.
>
> Python 3 behaves this way without the need for a future-import.
>
> If you omit the future-import in Python 2.7, `import config` will import
> the neighboring app/config.py by default, and there is no way to import
> the top-level config.py.
Thanks for setting me straight Carl.
I'm including the full package constructor (app/__init__.py) code
for other's edification and further comment (if deemed necessary).
Some commented annotation added
##################################################################
from __future__ import absolute_import
from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
# Import top-level config
from config import config
# Import same-level config avoiding name collision
from . import config as cfg
bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bootstrap.init_app(app)
mail.init_app(app)
moment.init_app(app)
db.init_app(app)
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
return app
Cheers
--
Tim
http://www.akwebsoft.com, http://www.tj49.com
More information about the Python-list
mailing list