2023-02-15 17:34:49 +04:00
|
|
|
"""Flask app error handlers"""
|
|
|
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
|
|
|
from flask import Flask
|
|
|
|
from flask import render_template
|
|
|
|
|
2023-02-15 19:55:06 +04:00
|
|
|
from . import routes
|
|
|
|
|
2023-02-15 17:34:49 +04:00
|
|
|
# Add other HTTP error codes here
|
|
|
|
CODES = [404, 500]
|
|
|
|
|
|
|
|
|
2023-02-15 19:55:06 +04:00
|
|
|
class RouteErrors(routes.Routes):
|
|
|
|
"""Error handlers wrapped in Routes interface"""
|
|
|
|
|
|
|
|
def __init__(self, app: Flask) -> None:
|
2023-02-15 17:34:49 +04:00
|
|
|
|
2023-02-15 19:55:06 +04:00
|
|
|
super().__init__(app)
|
2023-02-15 17:34:49 +04:00
|
|
|
|
2023-02-15 19:55:06 +04:00
|
|
|
tmpl_dir = self.app.template_folder
|
|
|
|
if tmpl_dir is None:
|
|
|
|
return
|
2023-02-15 17:34:49 +04:00
|
|
|
|
2023-02-15 19:55:06 +04:00
|
|
|
self.tmpl = Path(__file__).parent / tmpl_dir
|
2023-02-15 17:34:49 +04:00
|
|
|
|
2023-02-15 19:55:06 +04:00
|
|
|
def add_routes(self) -> None:
|
|
|
|
"""Add all error handlers"""
|
2023-02-15 17:34:49 +04:00
|
|
|
|
2023-02-15 19:55:06 +04:00
|
|
|
for code in CODES:
|
|
|
|
self.add_handler(code)
|
2023-02-15 17:34:49 +04:00
|
|
|
|
2023-02-15 19:55:06 +04:00
|
|
|
def add_handler(self, code: int) -> None:
|
|
|
|
"""Add Flask app error handler.
|
|
|
|
Only for internal use
|
2023-02-15 17:34:49 +04:00
|
|
|
|
2023-02-15 19:55:06 +04:00
|
|
|
Args:
|
|
|
|
code (int): HTTP error code
|
|
|
|
"""
|
2023-02-15 17:34:49 +04:00
|
|
|
|
2023-02-15 19:55:06 +04:00
|
|
|
file = f'{code}.html'
|
2023-02-15 17:34:49 +04:00
|
|
|
|
2023-02-15 19:55:06 +04:00
|
|
|
if (self.tmpl / file).exists():
|
2023-02-15 17:34:49 +04:00
|
|
|
|
2023-02-15 19:55:06 +04:00
|
|
|
@self.app.errorhandler(code)
|
|
|
|
def handler(_e):
|
|
|
|
return render_template(file), code
|