2016-04-28 13 views
1

我正在閱讀Flask示例,該示例從單個腳本應用程序轉換到應用程序工廠,因此引入了藍圖。使用藍圖的原因是因爲應用程序實例現在是在運行時創建的,而不是在全局範圍中存在(如在單個腳本應用程序中)。這會導致app.route裝飾器在調用create_app()之後存在,本書指出這太晚了。爲什麼在調用create_app()之後,app.route修飾器存在爲時已晚?爲什麼我們要在調用create_app()之前訪問路線?爲什麼在創建應用程序實例之前訪問應用程序路徑

回答

0

當您編寫應用程序工廠時,在調用工廠之前您沒有應用程序實例。工廠只在運行服務器時被調用,但您需要在運行服務器之前定義之前的。因此,您將它們附加到藍圖上,並在工廠中的應用程序上註冊藍圖。

# this would fail, app doesn't exist 
@app.route('/blog/<int:id>') 
def post(id): 
    ... 

# this works because the route is registered on the blueprint 
# which is later registered on the app 
blog_bp = Blueprint('blog', __name__, url_prefix='/blog') 

@blog_bp.route('/<int:id>') 
def post(id): 
    ... 

def create_app(): 
    app = Flask(__name__) 
    ... 
    app.register_blueprint(blog_bp) 
    ... 
    return app 

# app still doesn't exist, it only exists when the server uses the factory 
+0

你的意思是「這是因爲路線是在藍圖上註冊的嗎」? – Brosef

相關問題