2015-05-15 21 views
1

我試圖從以下包結構導入noun0.routes,但我得到ImportError: cannot import name db。爲什麼我得到這個錯誤,我該如何解決?導入兩個級別時導入錯誤

├── 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 
from flask.ext.sqlalchemy import SQLAlchemy 

from 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 
+0

由於切換到瓶號錯誤已被發現:) –

+0

雖然切換到瓶子幫助你很棒,但這不是一個真正有效的解決方案,另外,目前還不清楚在這種情況下如何切換瓶子會有所幫助,因爲這是一個導入問題,不是一個框架問題,我的答案是否幫助你理解實際問題是什麼? – davidism

回答

2

你已經創建了一個圓形的進口情況。 __init__.py進口noun0.routes,其中進口noun0.models,它試圖導入db。然而,__init__.py尚未達到定義db的點,它仍在嘗試完成導入。

在所有定義(或其導入鏈)依賴於它們之後移動路由導入。

app = Flask(__name__) 
db = SQLAlchemy(app) 

from some_rest_api.noun0.routes import noun0_api 

app.register_blueprint(noun0_api) 

This situation is mentioned in the Flask docs at the bottom of this page.


我改變你的進口從from noun0.routesfrom some_rest_api.noun0.routes。您正在使用舊的,容易出錯的相對導入模式。在Python 3中刪除了這種行爲。使用絕對導入總是比較好(如我所做的那樣),或者使用點符號表示相對導入:from .. import db表示「從我的位置上升兩級」