Обработка HTTP-ошибок 404, 500 и т.д. во Flask.
Если какая-то часть кода кода сайта на Flask ломается при обработке запроса и нет зарегистрированных обработчиков ошибок, то по умолчанию будет возвращена ошибка 500 Internal Server Error
(InternalServerError
). Точно так же будет выводится стандартная страница с ошибкой 404 Not Found
, если запрос будет отправлен на незарегистрированный URL-адрес. Если маршрут получает недопустимый метод запроса, будет активирован HTTP-метод 405 Not Allowed
. Все это подклассы HTTPException
, которые по умолчанию предоставляются в Flask.
Фреймворк Flask дает возможность вызывать любое исключение HTTP, зарегистрированное Werkzeug
, но по умолчанию отдаются простые/стандартные страницы ошибок. Для удобства пользователя сайта, а так же повышения лояльности поисковых систем к сайту необходимо показывать настроенные страницы ошибок (вместо стандартных). Это можно сделать, зарегистрировав обработчики ошибок.
Обработчик ошибок — это функция, которая возвращает ответ при возникновении определенного типа ошибки, аналогично тому, как представление является функцией, которая возвращает ответ при совпадении URL-адреса запроса. Ему передается экземпляр обрабатываемой ошибки, который будет является исключением werkzeug.exceptions.HTTPException
.
Когда Flask перехватывает исключение при обработке запроса, сначала выполняется поиск по коду. Если в коде не зарегистрирован обработчик, то Flask ищет ошибку в иерархии классов и выбирает наиболее конкретный обработчик. В том случае, если обработчик не зарегистрирован, то подклассы HTTPException
показывают наиболее подходящую стандартную страницу с ошибкой, в то время как другие исключения преобразуются в общую страницу 500 Internal Server Error
.
Например, если возникает экземпляр ConnectionRefusedError
и зарегистрированы обработчики ConnectionError
и ConnectionRefusedError
, то для генерации ответа будет вызываться более конкретный обработчик ConnectionRefusedError
.
Содержание.
- Регистрация обработчика ошибок в веб-приложении на Flask;
- Универсальные обработчики исключений во Flask;
- Как Flask обрабатывает необработанные исключения?
- Создание собственной страницы с HTTP-ошибкой 404;
- Пример пользовательской страницы ошибки с кодом 500;
- Особенности обработки ошибок в схемах
blueprint
Flask; - Возврат ошибок API в формате JSON.
Регистрация обработчика ошибок в веб-приложении на Flask.
Зарегистрировать функцию-обработчик для модуля Flask, можно указав перед ней декоратор @app.errorhandler()
, или зарегистрировать обработчик, использовав функцию app.register_error_handler()
. Не забудьте установить код ошибки при возврате ответа.
# регистрируем обработчик `handle_bad_request()` декоратором @app.errorhandler(werkzeug.exceptions.BadRequest) def handle_bad_request(e): return 'bad request!', 400 # регистрируем тот же обработчик без декоратора app.register_error_handler(400, handle_bad_request)
Подклассы HTTPException
, такие как BadRequest
и их HTTP-коды, взаимозаменяемы при регистрации обработчиков. (BadRequest.code == 400
)
Нестандартные HTTP-коды (такие как HTTP 507 Insufficient Storage
) нельзя зарегистрировать, так как они не известны модулю Werkzeug
. Для регистрации неизвестных HTTP-кодов определите подкласс werkzeug.exceptions.HTTPException
с соответствующим кодом, зарегистрируйте и где надо вернуть HTTP-код 507 Insufficient Storage
принудительно вызовите этот класс исключения при помощи инструкции raise
.
# создаем подкласс исключения HTTP 507 class InsufficientStorage(werkzeug.exceptions.HTTPException): code = 507 description = 'Not enough storage space.' # регистрируем HTTP 507 app.register_error_handler(InsufficientStorage, handle_507) # принудительно вызываем исключение `InsufficientStorage` raise InsufficientStorage()
Обработчики могут быть зарегистрированы для любого класса исключений, а не только для подклассов HTTPException
или кодов состояния HTTP. Обработчики могут быть зарегистрированы для определенного класса или для всех подклассов родительского класса.
Обработчики, зарегистрированные в blueprint
, имеют приоритет над обработчиками, зарегистрированными глобально в веб-приложении, при условии, что blueprint
(схема) обрабатывает запрос, вызывающий исключение. Однако blueprint
не может обрабатывать ошибки маршрутизации 404, так как ошибка 404 возникает на уровне маршрутизации до того, как можно определить схему blueprint
.
Универсальные обработчики исключений.
Можно зарегистрировать обработчики ошибок для очень общих базовых классов, таких как HTTPException
или даже Exception
, но имейте в виду, что они будут ловить все ошибки подряд (больше, чем можно ожидать) и в итоге получится одна страница ошибки на разные ситуации.
Например, обработчик ошибок для HTTPException
может быть полезен для преобразования страниц ошибок HTML по умолчанию в JSON. Но тогда этот обработчик будет запускать, например ошибки 404 и 405 во время маршрутизации. В общем будьте внимательны при создании универсальных обработчиков.
from flask import json from werkzeug.exceptions import HTTPException @app.errorhandler(HTTPException) def handle_exception(e): """Возвращает JSON вместо HTML для ошибок HTTP""" # сначала перехватываем ответ Flask для извлечения # правильных заголовков и кода состояния из ошибки response = e.get_response() # заменяем тело ответа сервера на JSON response.data = json.dumps({ "code": e.code, "name": e.name, "description": e.description, }) response.content_type = "application/json" # возвращаем ответ сервера return response
Обработчик ошибок для Exception
может !показаться! полезным для изменения способа представления пользователю всех ошибок, даже не перехваченных в коде. Другими словами: страница ошибки с одним и тем же HTTP-кодом для разных ситуаций (о чем говорилось выше). Исключение Exception
в Python фиксирует все необработанные ошибки, при этом будут включены все коды состояния HTTP.
Правильнее будет безопаснее зарегистрировать обработчики для более конкретных исключений, т.к. экземпляры HTTPException
являются действительными ответами WSGI.
from werkzeug.exceptions import HTTPException @app.errorhandler(Exception) def handle_exception(e): # исключаем ошибки HTTP if isinstance(e, HTTPException): # если это ошибка HTTP, то просто # возвращаем ее без изменений return e # в остальных случаях (ошибка кода веб-приложения) # генерируем страницу с ошибкой HTTP 500 return render_template("500_generic.html", e=e), 500
Обработчики ошибок по-прежнему соблюдают иерархию классов исключений. Если зарегистрировать обработчики как для HTTPException
, так и для Exception
, то обработчик Exception
не будет обрабатывать подклассы HTTPException
, т.к. он является более конкретным обработчиком HTTPException
.
Как Flask обрабатывает необработанные исключения?
Если код сайта на Flask во время работы ломается, то есть возникло исключение, для которого не зарегистрирован обработчик ошибок, то будет возвращена ошибка 500 Internal Server
Если для исключения InternalServerError
зарегистрирован обработчик ошибок, то будет вызван этот обработчик. Начиная с Flask 1.1.0, этому обработчику ошибок всегда будет передаваться экземпляр InternalServerError
, а не исходная не перехваченная ошибка. Исходная ошибка доступна как e.original_exception
.
Обработчику ошибок 500 Internal Server Error
будут передаваться неперехваченные исключения в дополнение к явным ошибкам 500. В режиме отладки обработчик 500 Internal Server Error
не используется, а показывается интерактивный отладчик.
Создание собственной страницы с HTTP-ошибкой 404.
Почти всегда при создании сайта на Flask необходимо потребоваться вызвать исключение HTTPException
, чтобы сообщить пользователю, что с запросом что-то не так. Фреймворк Flask поставляется с удобной функцией flask.abort()
, которая прерывает запрос со стандартной страницей HTTP-ошибки (только основное описание), зарегистрированной в модуле werkzeug
.
В зависимости от кода ошибки, вероятность того, что пользователь действительно увидит конкретную ошибку, меньше или больше.
Рассмотрим приведенный ниже код. Например, может быть маршрут профиля пользователя, и если пользователь не может передать имя пользователя, то можно выдать 400 Bad Request
. Если пользователь передает имя пользователя, а сайт не можем его найти, то выдаем сообщение 404 Not Found
.
from flask import abort, render_template, request # имя пользователя должно быть указано в параметрах запроса # успешный запрос будет похож на /profile?username=jack @app.route("/profile") def user_profile(): username = request.arg.get("username") # если имя пользователя не указано в запросе, # то вернем `400 Bad Request` if username is None: abort(400) user = get_user(username=username) # Если пользователь не наёден, то `404 not found` if user is None: abort(404) return render_template("profile.html", user=user)
Для того, что бы возвращалась страница 404 not found
с собственным дизайном, необходимо создать функцию обработчик:
from flask import render_template @app.errorhandler(404) def page_not_found(e): # в функцию `render_template()` передаем HTML-станицу с собственным # дизайном, а так же явно устанавливаем статус 404 return render_template('404.html'), 404
from flask import Flask, render_template # обработчик def page_not_found(e): return render_template('404.html'), 404 def create_app(config_filename): app = Flask(__name__) # регистрация обработчика app.register_error_handler(404, page_not_found) return app
Пример шаблона страницы с ошибкой 404.html
может быть таким:
{% extends "layout.html" %} {% block title %}Page Not Found{% endblock %} {% block body %} <h1>Page Not Found</h1> <h3>То, что вы искали, просто не существует.</h3> <p>Для продолжения перейдите <a href="{{ url_for('index') }}">на главную страницу сайта</a></p> {% endblock %}
Пример пользовательской страницы ошибки с кодом 500.
Приведенные выше примеры не на много улучшат страницы HTTP-ошибок по умолчанию. Так же можно создать собственный шаблон 500.html
следующим образом:
{% extends "layout.html" %} {% block title %}Internal Server Error{% endblock %} {% block body %} <h1>Internal Server Error</h1> <h3>Мы уже знаем об этой ошибке и делаем все возможное для ее устранения!</h3> <p>Приносим извинения за причлененные неудобства, скоро все заработает.</p> {% endblock %}
Создаем функцию обработчик HTTP-ошибок 500 Internal Server Error
:
from flask import render_template @app.errorhandler(500) def internal_server_error(e): # Обратите внимание, что необходимо # явно установить статус 500 return render_template('500.html'), 500
При использовании фабрик приложений:
from flask import Flask, render_template # обработчик def internal_server_error(e): return render_template('500.html'), 500 def create_app(): app = Flask(__name__) # регистрация обработчика app.register_error_handler(500, internal_server_error) return app
from flask import Blueprint blog = Blueprint('blog', __name__) # регистрация обработчика при помощи декоратора @blog.errorhandler(500) def internal_server_error(e): return render_template('500.html'), 500 # или с использованием метода `register_error_handler()` blog.register_error_handler(500, internal_server_error)
Особенности обработки ошибок в схемах blueprint
Flask.
В модульных приложениях с blueprint
большинство обработчиков ошибок будут работать должным образом, но есть предостережение относительно обработчиков исключений 404 и 405. Эти обработчики вызываются только из соответствующего оператора raise
или вызывают flask.abort()
в другой функции-представлении схемы blueprint
. Они не вызываются, например, из-за недействительного доступа к URL-адресу.
Это связано с тем, что blueprint
не принадлежит определенное пространство URL-адресов, поэтому экземпляр приложения не имеет возможности узнать, какой обработчик ошибок схемы (blueprint
) необходимо запустить, если указан недопустимый URL-адрес. Если необходимо использовать различные стратегии обработки этих ошибок на основе префиксов URL-адресов, то они могут быть определены на уровне приложения с помощью объекта прокси-сервера запроса flask.request
.
from flask import jsonify, render_template # на уровне всего веб-приложения # это не уровень определенной схемы blueprint @app.errorhandler(404) def page_not_found(e): # Если запрос находится в пространстве URL блога if request.path.startswith('/blog/'): # то возвращаем кастомную 404 ошибку для блога return render_template("blog/404.html"), 404 else: # в противном случае возвращаем # общую 404 ошибку для всего сайта return render_template("404.html"), 404 @app.errorhandler(405) def method_not_allowed(e): # Если в запросе указан неверный метод к API if request.path.startswith('/api/'): # возвращаем json с 405 HTTP-ошибкой return jsonify(message="Method Not Allowed"), 405 else: # в противном случае возвращаем # общую 405 ошибку для всего сайта return render_template("405.html"), 405
Возврат ошибок API в формате JSON
При создании API-интерфейсов во Flask некоторые разработчики понимают, что встроенные исключения недостаточно выразительны для API-интерфейсов и что тип содержимого text/html
, который они генерируют, не очень полезен для потребителей API.
Используя те же методы, что и выше плюс flask.jsonify()
, можно возвращать ответы JSON на ошибки API. Функция flask.abort()
вызывается с аргументом description
. Обработчик ошибок будет использовать это как сообщение об ошибке JSON и установит код состояния на 404.
from flask import abort, jsonify @app.errorhandler(404) def resource_not_found(e): return jsonify(error=str(e)), 404 @app.route("/cheese") def get_one_cheese(): resource = get_resource() if resource is None: abort(404, description="Resource not found") return jsonify(resource)
Можно создавать собственные классы исключений. Например, можно ввести новое настраиваемое исключение для API, которое будет принимать правильное удобочитаемое сообщение, код состояния для ошибки и некоторую дополнительную полезную информацию, чтобы дать больше конкретики для ошибки.
from flask import jsonify, request class InvalidAPIUsage(Exception): status_code = 400 def __init__(self, message, status_code=None, payload=None): super().__init__() self.message = message if status_code is not None: self.status_code = status_code self.payload = payload def to_dict(self): rv = dict(self.payload or ()) rv['message'] = self.message return rv @app.errorhandler(InvalidAPIUsage) def invalid_api_usage(e): return jsonify(e.to_dict()) # маршрут API для получения информации о пользователе # правильный запрос может быть /api/user?user_id=420 @app.route("/api/user") def user_api(user_id): user_id = request.arg.get("user_id") if not user_id: raise InvalidAPIUsage("No user id provided!") user = get_user(user_id=user_id) if not user: raise InvalidAPIUsage("No such user!", status_code=404) return jsonify(user.to_dict())
Теперь функция-представление может вызвать это исключение с сообщением об ошибке. Кроме того, дополнительная полезная информация может быть предоставлена в виде словаря через параметр payload
.
I have a website that uses Flask. It used to work well, but since recently, every request returns a 404, and it seems it can’t find the right endpoints. However:
- Locally, the site still works, only on my VPS it shows this strange behaviour.
url_for
works andapp.view_functions
contains all the routes as well.- And yet, I keep getting 404s on the VPS, even for
/
and anything under/static/
.
Here’s part of the code, it’s a bit much to show all of it and it’s not all relevant:
#snip
from flask import Flask, render_template, abort, request, redirect, url_for, session
from flask.ext.babelex import Babel
from flask.ext import babelex
#snip
app = Flask(__name__)
app.secret_key = #snip
#snip
#just one of the routes
@app.route('/')
def about():
return render_template('about.html')
#snip
@app.errorhandler(404)
def page_not_found(e):
#snip
return render_template('404.html'), 404
#snip
if __name__ == '__main__':
app.run(debug=True)
else:
app.config.update(
SERVER_NAME='snip.snip.com:80',
APPLICATION_ROOT='/',
)
asked Jun 26, 2014 at 18:02
7
I had the same issue. I had it because I changed the parameters SERVER_NAME
of the config to a name which is not the name of the server.
You can solve this bug by removing SERVER_NAME
from the config if you have it.
answered Aug 11, 2015 at 15:01
Alexis BenoistAlexis Benoist
2,3992 gold badges15 silver badges23 bronze badges
8
I know this is old, but I just ran into this same problem. Yours could be any number of issues but mine was that I had commented out the from app import views
line in my __init__.py
file. It gave me the same symptom: every endpoint that required @app.route
and a view was responding with 404’s. Static routes (.js and .css) were fine (that was my clue).
answered Dec 29, 2014 at 2:01
ScottScott
3,1643 gold badges31 silver badges40 bronze badges
1
Had the same issue because the following lines
if __name__ == '__main__':
app.run(host='127.0.0.1', threaded=True)
were declared before the function and decorator.
Moving these lines in the very bottom of file helped me.
answered Jul 9, 2019 at 7:47
AlveonaAlveona
7606 silver badges15 bronze badges
1
Extremely old by this point, but mine was related to bug in importing. I’m using blueprints and I had:
from app.auth import bp
instead of
from app.main import bp
I was importing the wrong bp/ routes
answered May 9, 2018 at 18:11
user7804097user7804097
3081 gold badge3 silver badges16 bronze badges
I received this error from defining my flask_restful route inside the create_app method. I still don’t quite understand why it didn’t work but once I changed the scope / moved it outside as shown below it worked.
from flask import Flask
from flask_restful import Resource
from extensions import db, api
from users.resources import User
def create_app():
app = Flask(__name__)
app.config.from_object('settings')
db.init_app(app)
api.init_app(app)
return app
api.add_resource(User, '/users')
answered Jun 14, 2018 at 3:02
Braden HoltBraden Holt
1,5141 gold badge18 silver badges30 bronze badges
Also check carefully the routes. If some does not end with a slash but you are calling it with a trailing slash, flask will return a 404.
I had this error following a url from an email client that (I don’t know why) append a trailing slash to the urls.
See documentation.
answered Aug 11, 2020 at 7:15
pvilaspvilas
6725 silver badges7 bronze badges
I had this problem and in my case it was about my templates
. I had an index page like this:
<div>
<a href="index.html">Home</a> |
<a href="login.html">Login</a> |
<a href="register.html">Register</a>
<hr>
</div>
I should have used url_for('index')
instead of index.html
.
<div>
<a href="{{ url_for('index') }}">Home</a> |
<a href="{{ url_for('login') }}">Login</a> |
<a href="{{ url_for('register') }}">Register</a>
<hr>
</div>
answered Jul 31, 2020 at 20:20
For me, I was getting 404s on every request due to missing favicon.ico
and manifest.json
. The solution was to provide the missing favicon.ico
, and remove the link rel refence to manifest.json
.
I found this out by printing the path that was causing problems on every request in my @app.errorhandler(Exception)
:
from flask import request
@app.errorhandler(Exception)
def handle_exception(err):
path = request.path # this var was shown to be 'favicon.ico' or 'manifest.json'
answered Jun 6, 2022 at 18:23
gene b.gene b.
9,72516 gold badges99 silver badges203 bronze badges
Prerequisite: Creating simple application in Flask
A 404 Error is showed whenever a page is not found. Maybe the owner changed its URL and forgot to change the link or maybe they deleted the page itself. Every site needs a Custom Error page to avoid the user to see the default Ugly Error page.
GeeksforGeeks also has a customized error page. If we type a URL like
www.geeksforgeeks.org/ajneawnewiaiowjf
Default 404 Error
GeeksForGeeks Customized Error Page
It will show an Error 404 page since this URL doesn’t exist. But an error page provides a beautiful layout, helps the user to go back, or even takes them to the homepage after a specific time interval. That is why Custom Error pages are necessary for every website.
Flask provides us with a way to handle the error and return our Custom Error page.
For this, we need to download and import flask. Download the flask through the following commands on CMD.
pip install flask
Using app.py as our Python file to manage templates, 404.html be the file we will return in the case of a 404 error and header.html be the file with header and navbar of a website.
app.py
Flask allows us to make a python file to define all routes and functions. In app.py we have defined the route to the main page (‘/’) and error handler function which is a flask function and we passed 404 error as a parameter.
from
flask
import
Flask, render_template
app
=
Flask(__name__)
@app
.errorhandler(
404
)
def
not_found(e):
return
render_template(
"404.html"
)
The above python program will return 404.html file whenever the user opens a broken link.
404.html
The following code exports header and navbar from header.html.
Both files should be stored in templates folder according to the flask.
{% extends "header.html" %}
{% block title %}Page Not Found{% endblock %}
{% block body %}
<
h1
>Oops! Looks like the page doesn't exist anymore</
h1
>
<
a
href
=
"{{ url_for('index') }}"
><
p
>Click Here</
a
>To go to the Home Page</
p
>
{% endblock %}
Automatically Redirecting to the Home page after 5 seconds
The app.py code for this example stays the same as above.
The following code Shows the Custom 404 Error page and starts a countdown of 5 seconds.
After 5 seconds are completed, it redirects the user back to the homepage.
404.html
The following code exports header and navbar from header.html.
Both files should be stored in the templates folder according to the flask.
After 5 seconds, the user will get redirected to the Home Page Automatically.
<
html
>
<
head
>
<
title
>Page Not Found</
title
>
<
script
language
=
"JavaScript"
type
=
"text/javascript"
>
var seconds =6;
// countdown timer. took 6 because page takes approx 1 sec to load
var url="{{url_for(index)}}";
// variable for index.html url
function redirect(){
if (seconds <=0){
// redirect to new url after counter down.
window.location = url;
} else {
seconds--;
document.getElementById("pageInfo").innerHTML="Redirecting to Home Page after "
+seconds+" seconds."
setTimeout("redirect()", 1000)
}
}
</
script
>
</
head
>
{% extends "header.html" %}
//exporting navbar and header from header.html
{% block body %}
<
body
onload
=
"redirect()"
>
<
p
id
=
"pageInfo"
></
p
>
{% endblock %}
</
html
>
Sample header.html
This is a sample header.html which includes a navbar just like shown in the image.
It’s made up of bootstrap. You can also make one of your own.
For this one, refer the bootstrap documentation.
<!DOCTYPE html>
<
html
>
<
head
>
css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E26
3XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin
=
"anonymous"
>
<
title
>Flask</
title
>
</
head
>
<
body
>
"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin
=
"anonymous"
></
script
>
/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K
/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin
=
"anonymous"
></
script
>
integrity
=
"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin
=
"anonymous"
></
script
>
<
header
>
<
nav
class
=
"navbar navbar-expand-lg navbar-light bg-light"
>
<
a
class
=
"navbar-brand"
href
=
"#"
>Navbar</
a
>
<
button
class
=
"navbar-toggler"
type
=
"button"
data-toggle
=
"collapse"
data-target
=
"#navbarSupportedContent"
aria-controls
=
"navbarSupportedContent"
aria-expanded
=
"false"
aria-label
=
"Toggle navigation"
>
<
span
class
=
"navbar-toggler-icon"
></
span
>
</
button
>
<
div
class
=
"collapse navbar-collapse"
id
=
"navbarSupportedContent"
>
<
ul
class
=
"navbar-nav mr-auto"
>
<
li
class
=
"nav-item active"
>
<
a
class
=
"nav-link"
href
=
"#"
>Home <
span
class
=
"sr-only"
>(current)</
span
></
a
>
</
li
>
<
li
class
=
"nav-item"
>
<
a
class
=
"nav-link"
href
=
"#"
>Link</
a
>
</
li
>
<
li
class
=
"nav-item dropdown"
>
<
a
class
=
"nav-link dropdown-toggle"
href
=
"#"
id
=
"navbarDropdown"
role
=
"button data-toggle="
dropdown"
aria-haspopup
=
"true"
aria-expanded
=
"false"
>
Dropdown
</
a
>
<
div
class
=
"dropdown-menu"
aria-labelledby
=
"navbarDropdown"
>
<
a
class
=
"dropdown-item"
href
=
"#"
>Action</
a
>
<
a
class
=
"dropdown-item"
href
=
"#"
>Another action</
a
>
<
div
class
=
"dropdown-divider"
></
div
>
<
a
class
=
"dropdown-item"
href
=
"#"
>Something else here</
a
>
</
div
>
</
li
>
<
li
class
=
"nav-item"
>
<
a
class
=
"nav-link disabled"
href
=
"#"
>Disabled</
a
>
</
li
>
</
ul
>
<
form
class
=
"form-inline my-2 my-lg-0"
>
<
input
class
=
"form-control mr-sm-2"
type
=
"search"
placeholder
=
"Search"
aria-label
=
"Search"
>
<
button
class
=
"btn btn-outline-success my-2 my-sm-0"
type
=
"submit"
>Search</
button
>
</
form
>
</
div
>
</
nav
>
</
head
>
<
body
>
{%block body%}
{%endblock%}
</
body
>
</
html
>
Output:
The output will be a custom error page with header.html that the user exported.
The following is an example output with my custom header, footer, and 404.html file.
Handling Application Errors
Applications fail, servers fail. Sooner or later you will see an exception
in production. Even if your code is 100% correct, you will still see
exceptions from time to time. Why? Because everything else involved will
fail. Here are some situations where perfectly fine code can lead to server
errors:
- the client terminated the request early and the application was still
reading from the incoming data - the database server was overloaded and could not handle the query
- a filesystem is full
- a harddrive crashed
- a backend server overloaded
- a programming error in a library you are using
- network connection of the server to another system failed
And that’s just a small sample of issues you could be facing. So how do we
deal with that sort of problem? By default if your application runs in
production mode, and an exception is raised Flask will display a very simple
page for you and log the exception to the :attr:`~flask.Flask.logger`.
But there is more you can do, and we will cover some better setups to deal
with errors including custom exceptions and 3rd party tools.
Error Logging Tools
Sending error mails, even if just for critical ones, can become
overwhelming if enough users are hitting the error and log files are
typically never looked at. This is why we recommend using Sentry for dealing with application errors. It’s
available as a source-available project on GitHub and is also available as a hosted version which you can try for free. Sentry
aggregates duplicate errors, captures the full stack trace and local
variables for debugging, and sends you mails based on new errors or
frequency thresholds.
To use Sentry you need to install the sentry-sdk
client with extra
flask
dependencies.
$ pip install sentry-sdk[flask]
And then add this to your Flask app:
import sentry_sdk from sentry_sdk.integrations.flask import FlaskIntegration sentry_sdk.init('YOUR_DSN_HERE', integrations=[FlaskIntegration()])
The YOUR_DSN_HERE
value needs to be replaced with the DSN value you
get from your Sentry installation.
After installation, failures leading to an Internal Server Error
are automatically reported to Sentry and from there you can
receive error notifications.
See also:
- Sentry also supports catching errors from a worker queue
(RQ, Celery, etc.) in a similar fashion. See the Python SDK docs for more information. - Getting started with Sentry
- Flask-specific documentation
Error Handlers
When an error occurs in Flask, an appropriate HTTP status code will be
returned. 400-499 indicate errors with the client’s request data, or
about the data requested. 500-599 indicate errors with the server or
application itself.
You might want to show custom error pages to the user when an error occurs.
This can be done by registering error handlers.
An error handler is a function that returns a response when a type of error is
raised, similar to how a view is a function that returns a response when a
request URL is matched. It is passed the instance of the error being handled,
which is most likely a :exc:`~werkzeug.exceptions.HTTPException`.
The status code of the response will not be set to the handler’s code. Make
sure to provide the appropriate HTTP status code when returning a response from
a handler.
Registering
Register handlers by decorating a function with
:meth:`~flask.Flask.errorhandler`. Or use
:meth:`~flask.Flask.register_error_handler` to register the function later.
Remember to set the error code when returning the response.
@app.errorhandler(werkzeug.exceptions.BadRequest) def handle_bad_request(e): return 'bad request!', 400 # or, without the decorator app.register_error_handler(400, handle_bad_request)
:exc:`werkzeug.exceptions.HTTPException` subclasses like
:exc:`~werkzeug.exceptions.BadRequest` and their HTTP codes are interchangeable
when registering handlers. (BadRequest.code == 400
)
Non-standard HTTP codes cannot be registered by code because they are not known
by Werkzeug. Instead, define a subclass of
:class:`~werkzeug.exceptions.HTTPException` with the appropriate code and
register and raise that exception class.
class InsufficientStorage(werkzeug.exceptions.HTTPException): code = 507 description = 'Not enough storage space.' app.register_error_handler(InsufficientStorage, handle_507) raise InsufficientStorage()
Handlers can be registered for any exception class, not just
:exc:`~werkzeug.exceptions.HTTPException` subclasses or HTTP status
codes. Handlers can be registered for a specific class, or for all subclasses
of a parent class.
Handling
When building a Flask application you will run into exceptions. If some part
of your code breaks while handling a request (and you have no error handlers
registered), a «500 Internal Server Error»
(:exc:`~werkzeug.exceptions.InternalServerError`) will be returned by default.
Similarly, «404 Not Found»
(:exc:`~werkzeug.exceptions.NotFound`) error will occur if a request is sent to an unregistered route.
If a route receives an unallowed request method, a «405 Method Not Allowed»
(:exc:`~werkzeug.exceptions.MethodNotAllowed`) will be raised. These are all
subclasses of :class:`~werkzeug.exceptions.HTTPException` and are provided by
default in Flask.
Flask gives you the ability to raise any HTTP exception registered by
Werkzeug. However, the default HTTP exceptions return simple exception
pages. You might want to show custom error pages to the user when an error occurs.
This can be done by registering error handlers.
When Flask catches an exception while handling a request, it is first looked up by code.
If no handler is registered for the code, Flask looks up the error by its class hierarchy; the most specific handler is chosen.
If no handler is registered, :class:`~werkzeug.exceptions.HTTPException` subclasses show a
generic message about their code, while other exceptions are converted to a
generic «500 Internal Server Error».
For example, if an instance of :exc:`ConnectionRefusedError` is raised,
and a handler is registered for :exc:`ConnectionError` and
:exc:`ConnectionRefusedError`, the more specific :exc:`ConnectionRefusedError`
handler is called with the exception instance to generate the response.
Handlers registered on the blueprint take precedence over those registered
globally on the application, assuming a blueprint is handling the request that
raises the exception. However, the blueprint cannot handle 404 routing errors
because the 404 occurs at the routing level before the blueprint can be
determined.
Generic Exception Handlers
It is possible to register error handlers for very generic base classes
such as HTTPException
or even Exception
. However, be aware that
these will catch more than you might expect.
For example, an error handler for HTTPException
might be useful for turning
the default HTML errors pages into JSON. However, this
handler will trigger for things you don’t cause directly, such as 404
and 405 errors during routing. Be sure to craft your handler carefully
so you don’t lose information about the HTTP error.
from flask import json from werkzeug.exceptions import HTTPException @app.errorhandler(HTTPException) def handle_exception(e): """Return JSON instead of HTML for HTTP errors.""" # start with the correct headers and status code from the error response = e.get_response() # replace the body with JSON response.data = json.dumps({ "code": e.code, "name": e.name, "description": e.description, }) response.content_type = "application/json" return response
An error handler for Exception
might seem useful for changing how
all errors, even unhandled ones, are presented to the user. However,
this is similar to doing except Exception:
in Python, it will
capture all otherwise unhandled errors, including all HTTP status
codes.
In most cases it will be safer to register handlers for more
specific exceptions. Since HTTPException
instances are valid WSGI
responses, you could also pass them through directly.
from werkzeug.exceptions import HTTPException @app.errorhandler(Exception) def handle_exception(e): # pass through HTTP errors if isinstance(e, HTTPException): return e # now you're handling non-HTTP exceptions only return render_template("500_generic.html", e=e), 500
Error handlers still respect the exception class hierarchy. If you
register handlers for both HTTPException
and Exception
, the
Exception
handler will not handle HTTPException
subclasses
because it the HTTPException
handler is more specific.
Unhandled Exceptions
When there is no error handler registered for an exception, a 500
Internal Server Error will be returned instead. See
:meth:`flask.Flask.handle_exception` for information about this
behavior.
If there is an error handler registered for InternalServerError
,
this will be invoked. As of Flask 1.1.0, this error handler will always
be passed an instance of InternalServerError
, not the original
unhandled error.
The original error is available as e.original_exception
.
An error handler for «500 Internal Server Error» will be passed uncaught
exceptions in addition to explicit 500 errors. In debug mode, a handler
for «500 Internal Server Error» will not be used. Instead, the
interactive debugger will be shown.
Custom Error Pages
Sometimes when building a Flask application, you might want to raise a
:exc:`~werkzeug.exceptions.HTTPException` to signal to the user that
something is wrong with the request. Fortunately, Flask comes with a handy
:func:`~flask.abort` function that aborts a request with a HTTP error from
werkzeug as desired. It will also provide a plain black and white error page
for you with a basic description, but nothing fancy.
Depending on the error code it is less or more likely for the user to
actually see such an error.
Consider the code below, we might have a user profile route, and if the user
fails to pass a username we can raise a «400 Bad Request». If the user passes a
username and we can’t find it, we raise a «404 Not Found».
from flask import abort, render_template, request # a username needs to be supplied in the query args # a successful request would be like /profile?username=jack @app.route("/profile") def user_profile(): username = request.arg.get("username") # if a username isn't supplied in the request, return a 400 bad request if username is None: abort(400) user = get_user(username=username) # if a user can't be found by their username, return 404 not found if user is None: abort(404) return render_template("profile.html", user=user)
Here is another example implementation for a «404 Page Not Found» exception:
from flask import render_template @app.errorhandler(404) def page_not_found(e): # note that we set the 404 status explicitly return render_template('404.html'), 404
When using :doc:`/patterns/appfactories`:
from flask import Flask, render_template def page_not_found(e): return render_template('404.html'), 404 def create_app(config_filename): app = Flask(__name__) app.register_error_handler(404, page_not_found) return app
An example template might be this:
{% extends "layout.html" %} {% block title %}Page Not Found{% endblock %} {% block body %} <h1>Page Not Found</h1> <p>What you were looking for is just not there. <p><a href="{{ url_for('index') }}">go somewhere nice</a> {% endblock %}
Further Examples
The above examples wouldn’t actually be an improvement on the default
exception pages. We can create a custom 500.html template like this:
{% extends "layout.html" %} {% block title %}Internal Server Error{% endblock %} {% block body %} <h1>Internal Server Error</h1> <p>Oops... we seem to have made a mistake, sorry!</p> <p><a href="{{ url_for('index') }}">Go somewhere nice instead</a> {% endblock %}
It can be implemented by rendering the template on «500 Internal Server Error»:
from flask import render_template @app.errorhandler(500) def internal_server_error(e): # note that we set the 500 status explicitly return render_template('500.html'), 500
When using :doc:`/patterns/appfactories`:
from flask import Flask, render_template def internal_server_error(e): return render_template('500.html'), 500 def create_app(): app = Flask(__name__) app.register_error_handler(500, internal_server_error) return app
When using :doc:`/blueprints`:
from flask import Blueprint blog = Blueprint('blog', __name__) # as a decorator @blog.errorhandler(500) def internal_server_error(e): return render_template('500.html'), 500 # or with register_error_handler blog.register_error_handler(500, internal_server_error)
Blueprint Error Handlers
In :doc:`/blueprints`, most error handlers will work as expected.
However, there is a caveat concerning handlers for 404 and 405
exceptions. These error handlers are only invoked from an appropriate
raise
statement or a call to abort
in another of the blueprint’s
view functions; they are not invoked by, e.g., an invalid URL access.
This is because the blueprint does not «own» a certain URL space, so
the application instance has no way of knowing which blueprint error
handler it should run if given an invalid URL. If you would like to
execute different handling strategies for these errors based on URL
prefixes, they may be defined at the application level using the
request
proxy object.
from flask import jsonify, render_template # at the application level # not the blueprint level @app.errorhandler(404) def page_not_found(e): # if a request is in our blog URL space if request.path.startswith('/blog/'): # we return a custom blog 404 page return render_template("blog/404.html"), 404 else: # otherwise we return our generic site-wide 404 page return render_template("404.html"), 404 @app.errorhandler(405) def method_not_allowed(e): # if a request has the wrong method to our API if request.path.startswith('/api/'): # we return a json saying so return jsonify(message="Method Not Allowed"), 405 else: # otherwise we return a generic site-wide 405 page return render_template("405.html"), 405
Returning API Errors as JSON
When building APIs in Flask, some developers realise that the built-in
exceptions are not expressive enough for APIs and that the content type of
:mimetype:`text/html` they are emitting is not very useful for API consumers.
Using the same techniques as above and :func:`~flask.json.jsonify` we can return JSON
responses to API errors. :func:`~flask.abort` is called
with a description
parameter. The error handler will
use that as the JSON error message, and set the status code to 404.
from flask import abort, jsonify @app.errorhandler(404) def resource_not_found(e): return jsonify(error=str(e)), 404 @app.route("/cheese") def get_one_cheese(): resource = get_resource() if resource is None: abort(404, description="Resource not found") return jsonify(resource)
We can also create custom exception classes. For instance, we can
introduce a new custom exception for an API that can take a proper human readable message,
a status code for the error and some optional payload to give more context
for the error.
This is a simple example:
from flask import jsonify, request class InvalidAPIUsage(Exception): status_code = 400 def __init__(self, message, status_code=None, payload=None): super().__init__() self.message = message if status_code is not None: self.status_code = status_code self.payload = payload def to_dict(self): rv = dict(self.payload or ()) rv['message'] = self.message return rv @app.errorhandler(InvalidAPIUsage) def invalid_api_usage(e): return jsonify(e.to_dict()), e.status_code # an API app route for getting user information # a correct request might be /api/user?user_id=420 @app.route("/api/user") def user_api(user_id): user_id = request.arg.get("user_id") if not user_id: raise InvalidAPIUsage("No user id provided!") user = get_user(user_id=user_id) if not user: raise InvalidAPIUsage("No such user!", status_code=404) return jsonify(user.to_dict())
A view can now raise that exception with an error message. Additionally
some extra payload can be provided as a dictionary through the payload
parameter.
Logging
See :doc:`/logging` for information about how to log exceptions, such as
by emailing them to admins.
Debugging
See :doc:`/debugging` for information about how to debug errors in
development and production.
Prerequisite: Creating simple application in Flask
A 404 Error is showed whenever a page is not found. Maybe the owner changed its URL and forgot to change the link or maybe they deleted the page itself. Every site needs a Custom Error page to avoid the user to see the default Ugly Error page.
GeeksforGeeks also has a customized error page. If we type a URL like
www.geeksforgeeks.org/ajneawnewiaiowjf
Default 404 Error
GeeksForGeeks Customized Error Page
It will show an Error 404 page since this URL doesn’t exist. But an error page provides a beautiful layout, helps the user to go back, or even takes them to the homepage after a specific time interval. That is why Custom Error pages are necessary for every website.
Flask provides us with a way to handle the error and return our Custom Error page.
For this, we need to download and import flask. Download the flask through the following commands on CMD.
pip install flask
Using app.py as our Python file to manage templates, 404.html be the file we will return in the case of a 404 error and header.html be the file with header and navbar of a website.
app.py
Flask allows us to make a python file to define all routes and functions. In app.py we have defined the route to the main page (‘/’) and error handler function which is a flask function and we passed 404 error as a parameter.
from
flask
import
Flask, render_template
app
=
Flask(__name__)
@app
.errorhandler(
404
)
def
not_found(e):
return
render_template(
"404.html"
)
The above python program will return 404.html file whenever the user opens a broken link.
404.html
The following code exports header and navbar from header.html.
Both files should be stored in templates folder according to the flask.
{% extends "header.html" %}
{% block title %}Page Not Found{% endblock %}
{% block body %}
<
h1
>Oops! Looks like the page doesn't exist anymore</
h1
>
<
a
href
=
"{{ url_for('index') }}"
><
p
>Click Here</
a
>To go to the Home Page</
p
>
{% endblock %}
Automatically Redirecting to the Home page after 5 seconds
The app.py code for this example stays the same as above.
The following code Shows the Custom 404 Error page and starts a countdown of 5 seconds.
After 5 seconds are completed, it redirects the user back to the homepage.
404.html
The following code exports header and navbar from header.html.
Both files should be stored in the templates folder according to the flask.
After 5 seconds, the user will get redirected to the Home Page Automatically.
<
html
>
<
head
>
<
title
>Page Not Found</
title
>
<
script
language
=
"JavaScript"
type
=
"text/javascript"
>
var seconds =6;
// countdown timer. took 6 because page takes approx 1 sec to load
var url="{{url_for(index)}}";
// variable for index.html url
function redirect(){
if (seconds <=0){
// redirect to new url after counter down.
window.location = url;
} else {
seconds--;
document.getElementById("pageInfo").innerHTML="Redirecting to Home Page after "
+seconds+" seconds."
setTimeout("redirect()", 1000)
}
}
</
script
>
</
head
>
{% extends "header.html" %}
//exporting navbar and header from header.html
{% block body %}
<
body
onload
=
"redirect()"
>
<
p
id
=
"pageInfo"
></
p
>
{% endblock %}
</
html
>
Sample header.html
This is a sample header.html which includes a navbar just like shown in the image.
It’s made up of bootstrap. You can also make one of your own.
For this one, refer the bootstrap documentation.
<!DOCTYPE html>
<
html
>
<
head
>
css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E26
3XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin
=
"anonymous"
>
<
title
>Flask</
title
>
</
head
>
<
body
>
"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin
=
"anonymous"
></
script
>
/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K
/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin
=
"anonymous"
></
script
>
integrity
=
"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin
=
"anonymous"
></
script
>
<
header
>
<
nav
class
=
"navbar navbar-expand-lg navbar-light bg-light"
>
<
a
class
=
"navbar-brand"
href
=
"#"
>Navbar</
a
>
<
button
class
=
"navbar-toggler"
type
=
"button"
data-toggle
=
"collapse"
data-target
=
"#navbarSupportedContent"
aria-controls
=
"navbarSupportedContent"
aria-expanded
=
"false"
aria-label
=
"Toggle navigation"
>
<
span
class
=
"navbar-toggler-icon"
></
span
>
</
button
>
<
div
class
=
"collapse navbar-collapse"
id
=
"navbarSupportedContent"
>
<
ul
class
=
"navbar-nav mr-auto"
>
<
li
class
=
"nav-item active"
>
<
a
class
=
"nav-link"
href
=
"#"
>Home <
span
class
=
"sr-only"
>(current)</
span
></
a
>
</
li
>
<
li
class
=
"nav-item"
>
<
a
class
=
"nav-link"
href
=
"#"
>Link</
a
>
</
li
>
<
li
class
=
"nav-item dropdown"
>
<
a
class
=
"nav-link dropdown-toggle"
href
=
"#"
id
=
"navbarDropdown"
role
=
"button data-toggle="
dropdown"
aria-haspopup
=
"true"
aria-expanded
=
"false"
>
Dropdown
</
a
>
<
div
class
=
"dropdown-menu"
aria-labelledby
=
"navbarDropdown"
>
<
a
class
=
"dropdown-item"
href
=
"#"
>Action</
a
>
<
a
class
=
"dropdown-item"
href
=
"#"
>Another action</
a
>
<
div
class
=
"dropdown-divider"
></
div
>
<
a
class
=
"dropdown-item"
href
=
"#"
>Something else here</
a
>
</
div
>
</
li
>
<
li
class
=
"nav-item"
>
<
a
class
=
"nav-link disabled"
href
=
"#"
>Disabled</
a
>
</
li
>
</
ul
>
<
form
class
=
"form-inline my-2 my-lg-0"
>
<
input
class
=
"form-control mr-sm-2"
type
=
"search"
placeholder
=
"Search"
aria-label
=
"Search"
>
<
button
class
=
"btn btn-outline-success my-2 my-sm-0"
type
=
"submit"
>Search</
button
>
</
form
>
</
div
>
</
nav
>
</
head
>
<
body
>
{%block body%}
{%endblock%}
</
body
>
</
html
>
Output:
The output will be a custom error page with header.html that the user exported.
The following is an example output with my custom header, footer, and 404.html file.
Prerequisite: Creating simple application in Flask
A 404 Error is showed whenever a page is not found. Maybe the owner changed its URL and forgot to change the link or maybe they deleted the page itself. Every site needs a Custom Error page to avoid the user to see the default Ugly Error page.
GeeksforGeeks also has a customized error page. If we type a URL like
www.geeksforgeeks.org/ajneawnewiaiowjf
Default 404 Error
GeeksForGeeks Customized Error Page
It will show an Error 404 page since this URL doesn’t exist. But an error page provides a beautiful layout, helps the user to go back, or even takes them to the homepage after a specific time interval. That is why Custom Error pages are necessary for every website.
Flask provides us with a way to handle the error and return our Custom Error page.
For this, we need to download and import flask. Download the flask through the following commands on CMD.
pip install flask
Using app.py as our Python file to manage templates, 404.html be the file we will return in the case of a 404 error and header.html be the file with header and navbar of a website.
app.py
Flask allows us to make a python file to define all routes and functions. In app.py we have defined the route to the main page (‘/’) and error handler function which is a flask function and we passed 404 error as a parameter.
from
flask
import
Flask, render_template
app
=
Flask(__name__)
@app
.errorhandler(
404
)
def
not_found(e):
return
render_template(
"404.html"
)
The above python program will return 404.html file whenever the user opens a broken link.
404.html
The following code exports header and navbar from header.html.
Both files should be stored in templates folder according to the flask.
{% extends "header.html" %}
{% block title %}Page Not Found{% endblock %}
{% block body %}
<
h1
>Oops! Looks like the page doesn't exist anymore</
h1
>
<
a
href
=
"{{ url_for('index') }}"
><
p
>Click Here</
a
>To go to the Home Page</
p
>
{% endblock %}
Automatically Redirecting to the Home page after 5 seconds
The app.py code for this example stays the same as above.
The following code Shows the Custom 404 Error page and starts a countdown of 5 seconds.
After 5 seconds are completed, it redirects the user back to the homepage.
404.html
The following code exports header and navbar from header.html.
Both files should be stored in the templates folder according to the flask.
After 5 seconds, the user will get redirected to the Home Page Automatically.
<
html
>
<
head
>
<
title
>Page Not Found</
title
>
<
script
language
=
"JavaScript"
type
=
"text/javascript"
>
var seconds =6;
// countdown timer. took 6 because page takes approx 1 sec to load
var url="{{url_for(index)}}";
// variable for index.html url
function redirect(){
if (seconds <=0){
// redirect to new url after counter down.
window.location = url;
} else {
seconds--;
document.getElementById("pageInfo").innerHTML="Redirecting to Home Page after "
+seconds+" seconds."
setTimeout("redirect()", 1000)
}
}
</
script
>
</
head
>
{% extends "header.html" %}
//exporting navbar and header from header.html
{% block body %}
<
body
onload
=
"redirect()"
>
<
p
id
=
"pageInfo"
></
p
>
{% endblock %}
</
html
>
Sample header.html
This is a sample header.html which includes a navbar just like shown in the image.
It’s made up of bootstrap. You can also make one of your own.
For this one, refer the bootstrap documentation.
<!DOCTYPE html>
<
html
>
<
head
>
css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E26
3XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin
=
"anonymous"
>
<
title
>Flask</
title
>
</
head
>
<
body
>
"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin
=
"anonymous"
></
script
>
/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K
/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin
=
"anonymous"
></
script
>
integrity
=
"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin
=
"anonymous"
></
script
>
<
header
>
<
nav
class
=
"navbar navbar-expand-lg navbar-light bg-light"
>
<
a
class
=
"navbar-brand"
href
=
"#"
>Navbar</
a
>
<
button
class
=
"navbar-toggler"
type
=
"button"
data-toggle
=
"collapse"
data-target
=
"#navbarSupportedContent"
aria-controls
=
"navbarSupportedContent"
aria-expanded
=
"false"
aria-label
=
"Toggle navigation"
>
<
span
class
=
"navbar-toggler-icon"
></
span
>
</
button
>
<
div
class
=
"collapse navbar-collapse"
id
=
"navbarSupportedContent"
>
<
ul
class
=
"navbar-nav mr-auto"
>
<
li
class
=
"nav-item active"
>
<
a
class
=
"nav-link"
href
=
"#"
>Home <
span
class
=
"sr-only"
>(current)</
span
></
a
>
</
li
>
<
li
class
=
"nav-item"
>
<
a
class
=
"nav-link"
href
=
"#"
>Link</
a
>
</
li
>
<
li
class
=
"nav-item dropdown"
>
<
a
class
=
"nav-link dropdown-toggle"
href
=
"#"
id
=
"navbarDropdown"
role
=
"button data-toggle="
dropdown"
aria-haspopup
=
"true"
aria-expanded
=
"false"
>
Dropdown
</
a
>
<
div
class
=
"dropdown-menu"
aria-labelledby
=
"navbarDropdown"
>
<
a
class
=
"dropdown-item"
href
=
"#"
>Action</
a
>
<
a
class
=
"dropdown-item"
href
=
"#"
>Another action</
a
>
<
div
class
=
"dropdown-divider"
></
div
>
<
a
class
=
"dropdown-item"
href
=
"#"
>Something else here</
a
>
</
div
>
</
li
>
<
li
class
=
"nav-item"
>
<
a
class
=
"nav-link disabled"
href
=
"#"
>Disabled</
a
>
</
li
>
</
ul
>
<
form
class
=
"form-inline my-2 my-lg-0"
>
<
input
class
=
"form-control mr-sm-2"
type
=
"search"
placeholder
=
"Search"
aria-label
=
"Search"
>
<
button
class
=
"btn btn-outline-success my-2 my-sm-0"
type
=
"submit"
>Search</
button
>
</
form
>
</
div
>
</
nav
>
</
head
>
<
body
>
{%block body%}
{%endblock%}
</
body
>
</
html
>
Output:
The output will be a custom error page with header.html that the user exported.
The following is an example output with my custom header, footer, and 404.html file.