简体   繁体   中英

Flask Redirect URL for page not found (404 error)

I want to know which way is better to handle page not found error 404. So I have found two ways to redirect pages when someone tries to go to my website, bu they type in a url that I do not have a route built for. The first way is to build an error handler so I could do one like this:

@app.errorhandler(404)
def internal_error(error):
    return redirect(url_for('index'))

There is a second method that I found via the flask website, http://flask.pocoo.org/snippets/57/ , and is like this:

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
    return redirect(url_for('index'))

The difference is that one would be handling the error and the other is a dynamic routing. But what would be better to use? I don't really know what the pros of cons would be and before deploying one I would like to better understand it.

To help this is my base code:

@app.route('/', methods=["GET", "POST"])
def index():
  return render_template("HomePage.html")

if __name__ == "__main__":
  app.debug = True
  app.run()

I'll say to handle your scenario, the second approach is good as you need the handle the route that not exist

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
    return redirect(url_for('index')) 

But in general, both have different use-cases, let say, you are rendering multiple templates in different functions and you got an exception while rendering it. So, to cater this situation you need to do implement exception handling in all the method. Henceforth, instead of doing this and to make our readable and scalable, we can register the exception with this function and create a custom response for the user, refer below:

# It will catch the exception when the Template is not found and
# raise a custom response as per the rasied exception
@app.errorhandler(TemplateNotFound)
def handle_error(error):
    message = [str(x) for x in error.args]
    status_code = 500
    success = False
    response = {
        'success': success,
        'error': {
            'type': error.__class__.__name__,
            'message': message
        }
    }
    return jsonify(response), status_code

# For any other exception, it will send the reponse with a custom message 
@app.errorhandler(Exception)
def handle_unexpected_error(error):
    status_code = 500
    success = False
    response = {
        'success': success,
        'error': {
            'type': 'UnexpectedException',
            'message': 'An unexpected error has occurred.'
        }
    }

    return jsonify(response), status_code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM