about and errorpages

This commit is contained in:
Mateusz Gruszczyński
2026-05-06 11:06:08 +02:00
parent 1baf4a8495
commit 6587e74892
4 changed files with 249 additions and 1 deletions

View File

@@ -1,7 +1,7 @@
from __future__ import annotations
from pathlib import Path
from flask import Flask, request, url_for
from flask import Flask, jsonify, render_template, request, url_for
from flask_socketio import SocketIO
from werkzeug.middleware.proxy_fix import ProxyFix
from .config import (
@@ -22,6 +22,39 @@ socketio = SocketIO(cors_allowed_origins=SOCKETIO_CORS_ALLOWED_ORIGINS, ping_tim
_static_md5_cache: dict[tuple, str] = {}
def _wants_json_response() -> bool:
"""Return true for API/error clients that should not receive an HTML page."""
best = request.accept_mimetypes.best_match(["application/json", "text/html"])
return request.path.startswith("/api/") or best == "application/json"
def register_error_pages(app: Flask) -> None:
# Notatka: własne strony błędów zastępują generyczne 404/500 i zachowują JSON dla API.
@app.errorhandler(404)
def not_found(error):
if _wants_json_response():
return jsonify({"ok": False, "error": "Not found"}), 404
return render_template(
"error.html",
code=404,
title="Page not found",
message="The requested pyTorrent view does not exist or is not available.",
icon="fa-compass-drafting",
), 404
@app.errorhandler(500)
def server_error(error):
if _wants_json_response():
return jsonify({"ok": False, "error": "Internal server error"}), 500
return render_template(
"error.html",
code=500,
title="Application error",
message="pyTorrent hit an internal error while handling this request.",
icon="fa-bug",
), 500
def create_app() -> Flask:
app = Flask(__name__)
if PROXY_FIX_ENABLE:
@@ -71,6 +104,7 @@ def create_app() -> Flask:
from .routes.api import bp as api_bp
app.register_blueprint(main_bp)
app.register_blueprint(api_bp)
register_error_pages(app)
init_db()
from .services.auth import install_guards
install_guards(app)