Multiple 404 error pages using Python (Flask)

Is it possible to serve multiple 404 pages in python using a flask?

I currently have this in my views.py file:

@application.errorhandler(404)
def page_not_found(e):
    return render_template('errorpages/404.html'), 404

      

Is it possible to serve, for example, three random 404 pages instead of one? How?

Thanks in advance.

+3


source to share


1 answer


If you want your server to randomly select one of the three 404 pages to serve, you can do something like this:

import random

@application.errorhandler(404)
def page_not_found(e):
    return render_template(
        'errorpages/404_{}.html'.format(random.randint(0, 3)) ), 404

      

If your pages errorpages/404_1.html

, errorpages/404_2.html

anderrorpages/404_3.html




Or, if you wanted the page to serve as stateful, your code would look something like this:

@application.errorhandler(404)
def page_not_found(e):
    if condition:
        return render_template('errorpages/404_1.html'), 404
    return render_template('errorpages/404.html'), 404

      

+5


source







All Articles