From a937e08ef057f24c21c645f18b6df3688915fe1f Mon Sep 17 00:00:00 2001 From: Adam Hopkins Date: Sun, 12 Sep 2021 07:19:26 +0300 Subject: [PATCH] Add ability to return Falsey but not-None from handlers (#2236) --- sanic/app.py | 2 +- tests/test_middleware.py | 16 +++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/sanic/app.py b/sanic/app.py index 04383587..634ba665 100644 --- a/sanic/app.py +++ b/sanic/app.py @@ -839,7 +839,7 @@ class Sanic(BaseSanic, metaclass=TouchUpMeta): if isawaitable(response): response = await response - if response: + if response is not None: response = await request.respond(response) elif not hasattr(handler, "is_websocket"): response = request.stream.response # type: ignore diff --git a/tests/test_middleware.py b/tests/test_middleware.py index 1ae8fb6e..c19386e7 100644 --- a/tests/test_middleware.py +++ b/tests/test_middleware.py @@ -5,7 +5,7 @@ from itertools import count from sanic.exceptions import NotFound from sanic.request import Request -from sanic.response import HTTPResponse, text +from sanic.response import HTTPResponse, json, text # ------------------------------------------------------------ # @@ -283,3 +283,17 @@ def test_request_middleware_executes_once(app): request, response = app.test_client.get("/") assert next(i) == 3 + + +def test_middleware_added_response(app): + @app.on_response + def display(_, response): + response["foo"] = "bar" + return json(response) + + @app.get("/") + async def handler(request): + return {} + + _, response = app.test_client.get("/") + assert response.json["foo"] == "bar"