Skip to content

Commit

Permalink
Alow Blueprint routes to explicitly define error_format (#2773)
Browse files Browse the repository at this point in the history
Co-authored-by: Adam Hopkins <adam@amhopkins.com>
  • Loading branch information
moshe742 and ahopkins committed Jul 9, 2023
1 parent 976da69 commit 5dd1623
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
6 changes: 5 additions & 1 deletion sanic/blueprints.py
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,10 @@ def register(self, app, options):
# 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,
Expand Down Expand Up @@ -358,7 +362,7 @@ def register(self, app, options):
future.unquote,
future.static,
version_prefix,
error_format,
route_error_format,
future.route_context,
)

Expand Down
22 changes: 22 additions & 0 deletions tests/test_errorpages.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import pytest

import sanic
from sanic import Sanic
from sanic.config import Config
from sanic.errorpages import TextRenderer, exception_response, guess_mime
Expand Down Expand Up @@ -205,6 +206,27 @@ def json_response(request):
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"
Expand Down

0 comments on commit 5dd1623

Please sign in to comment.