python - ImportError when importing two levels up -
i trying import noun0.routes
following package structure importerror: cannot import name db
. why getting error , how fix it?
├── some_rest_api │ ├── noun0 │ │ ├── __init__.py │ │ ├── models.py │ │ ├── routes.py │ ├── noun1 │ │ ├── __init__.py │ │ ├── models.py │ │ ├── routes.py │ ├── routes.py │ ├── utils.py │ └── __init__.py ├── requirements.txt └── setup.py
some_rest_api/__init__.py
from flask import flask flask.ext.sqlalchemy import sqlalchemy noun0.routes import noun0_api app = flask(__name__) db = sqlalchemy(app) app.register_blueprint(noun0_api)
some_rest_api/noun0/models.py
from some_rest_api import db
you've created circular import situation. __init__.py
imports noun0.routes
, imports noun0.models
, tries import db
. however, __init__.py
hasn't reached point has defined db
, it's still trying complete import.
move route imports after definitions (or chain of imports) depend on.
app = flask(__name__) db = sqlalchemy(app) some_rest_api.noun0.routes import noun0_api app.register_blueprint(noun0_api)
this situation mentioned in flask docs @ bottom of page.
i changed import from noun0.routes
from some_rest_api.noun0.routes
. using old, error prone pattern of relative imports. behavior removed in python 3. better use absolute imports (as did), or use dot notation relative imports: from .. import db
says "go 2 levels am.
Comments
Post a Comment