简体   繁体   中英

how to redirect to a external 404 page python flask

I am trying to redirect my 404 to a external URL like this:

@app.route('404')
def http_error_handler(error):
    return flask.redirect("http://www.exemple.com/404"), 404

but it does not work. I keep getting:

Not Found The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

You should try something like this:

from flask import render_template

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404

Source http://flask.pocoo.org/docs/1.0/patterns/errorpages/

You cannot do this - the user-agent (in most cases, a browser) looks at the status code that is returned to determine what to do. When you return a 404 status code what you are saying to the user-agent is, "I don't know what this thing is you are requesting" and the user-agent can then:

  • Display what you return in the body of the response
  • Display its own error message to the end user
  • Do some combination of the above two options

redirect actually creates a little HTML response (via werkzeug.exceptions) , which normally the end user doesn't see because the user-agent follows the Location header when it sees the 302 response. However, you override the status code when you provide your own status code (404).

The fix is to either:

  • Remove the status code (at the cost of sending the wrong signal to the end user, potentially)
  • or Send a 404 with a meta:refresh and / or JavaScript redirect (slightly better, still confusing):

     return redirect("/where-ever"), 404, {"Refresh": "1; url=/where-ever"}

Try this instead of a route

from flask import request
@app.errorhandler(404)
def own_404_page(error):
    pageName =  request.args.get('url')
    print(pageName)
    print(error)
    f = open('erreur404.tpl')
    return f.read()

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