From 5dd1623192d9cff3f6aedc8e11e270073d589c40 Mon Sep 17 00:00:00 2001 From: Moshe Nahmias Date: Sun, 9 Jul 2023 14:47:59 +0300 Subject: [PATCH] Alow Blueprint routes to explicitly define error_format (#2773) Co-authored-by: Adam Hopkins --- sanic/blueprints.py | 6 +++++- tests/test_errorpages.py | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/sanic/blueprints.py b/sanic/blueprints.py index a52495b9..fc9408fe 100644 --- a/sanic/blueprints.py +++ b/sanic/blueprints.py @@ -319,6 +319,10 @@ class Blueprint(BaseSanic): # Prepend the blueprint URI prefix if available uri = self._setup_uri(future.uri, url_prefix) + route_error_format = ( + future.error_format if future.error_format else error_format + ) + version_prefix = self.version_prefix for prefix in ( future.version_prefix, @@ -358,7 +362,7 @@ class Blueprint(BaseSanic): future.unquote, future.static, version_prefix, - error_format, + route_error_format, future.route_context, ) diff --git a/tests/test_errorpages.py b/tests/test_errorpages.py index a2df90b3..6c4334b7 100644 --- a/tests/test_errorpages.py +++ b/tests/test_errorpages.py @@ -2,6 +2,7 @@ import logging import pytest +import sanic from sanic import Sanic from sanic.config import Config from sanic.errorpages import TextRenderer, exception_response, guess_mime @@ -205,6 +206,27 @@ def test_route_error_response_from_explicit_format(app): assert response.content_type == "text/plain; charset=utf-8" +def test_blueprint_error_response_from_explicit_format(app): + bp = sanic.Blueprint("MyBlueprint") + + @bp.get("/text", error_format="json") + def text_response(request): + raise Exception("oops") + return text("Never gonna see this") + + @bp.get("/json", error_format="text") + def json_response(request): + raise Exception("oops") + return json({"message": "Never gonna see this"}) + + app.blueprint(bp) + _, response = app.test_client.get("/text") + assert response.content_type == "application/json" + + _, response = app.test_client.get("/json") + assert response.content_type == "text/plain; charset=utf-8" + + def test_unknown_fallback_format(app): with pytest.raises(SanicException, match="Unknown format: bad"): app.config.FALLBACK_ERROR_FORMAT = "bad"