2013-04-05 155 views
3

我創建了簡單的多應用程序Flask站點。我將所有錯誤視圖(404,501等)移至應用程序errors。但是當發生錯誤時,我只能看到Flask的默認錯誤頁面,而不是我自己的。項目 結構是:Flask錯誤處理程序

/site 
|-> main.py 
    from flask import Flask 

    app = Flask(__name__) 
    app.config.from_pyfile('config.py') 

    import errors, account, mysite, blog 
    from errors.views import not_found 

    @app.route("/") 
    def index_view(): 
     return "Welcome!" 

    @app.route("/about") 
    def about_view(): 
     return "About" 

    if __name__ == "__main__": 
     app.run(debug=True) 
|-> templates 
    |-> errors 
    |-> 404.html 

|->errors 
    |-> __init__.py 
    from main import app 
    import errors.views 
    |-> views 
    from errors import app 
    from flask import render_template 

    @app.errorhandler(404) 
    def not_found(error): 
     return render_template('errors/404.html'), 404 

如果我回國的errors/views.py內容main.py它開始按預期方式工作,讓我看看我的錯誤頁面。

回答

3

將所有錯誤模板(如404等)放入項目的主模板文件夾中。所以,如果你的項目被稱爲「MyProject的」,你可以有這樣的:

myproject/ 
    __init__.py 
    templates 
     404.html 
     503.html 
     .. and so on 

調用這些在__init__.py文件:

app = Flask(__name__) 

@app.errorhandler(404) 
def not_found(error): 
    return render_template('404.html'), 404  
+0

這是顯而易見的,但沒有很好的解決辦法。如果我將另一個應用程序添加到項目中,我將面臨同樣的問題。這就是爲什麼我想從項目中分離事件錯誤的原因。 – 2013-04-07 09:14:58