Flask错误处理程序

Flask错误处理程序

问题描述:

我创建了简单的多应用程序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它开始按预期方式工作,让我看看我的错误页面。

将所有错误模板(如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