Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask error handler

Tags:

python

flask

web

I created simple multi-application Flask site. I moved all errors view (404, 501, etc.) to application errors. But when an error occures I see only default error pages of Flask, not my own. Structure of project is:

/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

If i returning content of errors/views.py to main.py it begins work as expected and show me my error page.

like image 724
Alex G.P. Avatar asked Nov 16 '25 17:11

Alex G.P.


1 Answers

Put all the error templates like 404 etc. in the main templates folder of your project. So if your project is called "myproject", you can have something like:

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

Call these in your __init__.py file as:

app = Flask(__name__)

@app.errorhandler(404)
def not_found(error):
    return render_template('404.html'), 404    
like image 57
codegeek Avatar answered Nov 19 '25 09:11

codegeek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!