Add ability to return Falsey but not-None from handlers (#2236)

This commit is contained in:
Adam Hopkins 2021-09-12 07:19:26 +03:00 committed by GitHub
parent ef4f058a6c
commit a937e08ef0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 2 deletions

View File

@ -839,7 +839,7 @@ class Sanic(BaseSanic, metaclass=TouchUpMeta):
if isawaitable(response): if isawaitable(response):
response = await response response = await response
if response: if response is not None:
response = await request.respond(response) response = await request.respond(response)
elif not hasattr(handler, "is_websocket"): elif not hasattr(handler, "is_websocket"):
response = request.stream.response # type: ignore response = request.stream.response # type: ignore

View File

@ -5,7 +5,7 @@ from itertools import count
from sanic.exceptions import NotFound from sanic.exceptions import NotFound
from sanic.request import Request 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("/") request, response = app.test_client.get("/")
assert next(i) == 3 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"