Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Flask 500 Internal Server Error page

from flask import Flask
app = Flask(__name__)

@app.route("/")
def main():
    return '''
Main
<a href="/bad">bad</a>
'''

@app.route("/bad")
def bad():
    raise Exception("This is a bad page")
    return 'Bad page'
import default_500
import pytest

@pytest.fixture()
def web():
    return default_500.app.test_client()

def test_app(web):
    rv = web.get('/')
    assert rv.status == '200 OK'
    assert b'<a href="/bad">bad</a>' in rv.data

def test_bad(web):
    rv = web.get('/bad')
    assert rv.status == '500 INTERNAL SERVER ERROR'
    assert b'<h1>Internal Server Error</h1>' in rv.data

Will not trigger in debug mode!

$ flask --app default_500 run
curl -I http://localhost:5000/not

HTTP/1.0 500 INTERNAL SERVER ERROR
from flask import Flask
app = Flask(__name__)

@app.route("/")
def main():
    return '''
Main
<a href="/bad">bad</a>
'''

@app.route("/bad")
def bad():
    raise Exception("This is a bad page")
    return 'Bad page'

@app.errorhandler(500)
def not_found(err):
    #raise Exception("There should not be an exception here!")
    return f"Our Page crashed <b>{err}</b>", 500
import handle_500
import pytest

@pytest.fixture()
def web():
    return handle_500.app.test_client()

def test_app(web):
    rv = web.get('/')
    assert rv.status == '200 OK'
    assert b'<a href="/bad">bad</a>' in rv.data

def test_bad(web):
    rv = web.get('/bad')
    assert rv.status == '500 INTERNAL SERVER ERROR'
    assert b'Our Page crashed' in rv.data
    assert b'<b>500 Internal Server Error: The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</b>' in rv.data

$ flask --app handle_500 run