From aa270d3ac26aea9b972005cb38e8211e67f1bd59 Mon Sep 17 00:00:00 2001 From: Adam Hopkins Date: Sun, 11 Aug 2019 11:27:59 +0300 Subject: [PATCH] Add content-type headers in response in ASGI mode --- sanic/asgi.py | 5 +++++ tests/test_asgi.py | 26 +++++++++++++++++++++++++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/sanic/asgi.py b/sanic/asgi.py index e9bcf2de..fbffcaa9 100644 --- a/sanic/asgi.py +++ b/sanic/asgi.py @@ -328,6 +328,11 @@ class ASGIApp: (b"content-length", str(len(response.body)).encode("latin-1")) ] + if "content-type" not in response.headers: + headers += [ + (b"content-type", str(response.content_type).encode("latin-1")) + ] + if response.cookies: cookies.update( { diff --git a/tests/test_asgi.py b/tests/test_asgi.py index 97542b07..bf024252 100644 --- a/tests/test_asgi.py +++ b/tests/test_asgi.py @@ -9,7 +9,7 @@ from sanic import Sanic from sanic.asgi import MockTransport from sanic.exceptions import InvalidUsage from sanic.request import Request -from sanic.response import text +from sanic.response import json, text from sanic.websocket import WebSocketConnection @@ -256,3 +256,27 @@ async def test_cookie_customization(app): assert cookie_map.get(k).get("value") == v.value if cookie_map.get(k).get("HttpOnly"): assert "HttpOnly" in v._rest.keys() + + +@pytest.mark.asyncio +async def test_json_content_type(app): + @app.get("/json") + def send_json(request): + return json({"foo": "bar"}) + + @app.get("/text") + def send_text(request): + return text("foobar") + + @app.get("/custom") + def send_custom(request): + return text("foobar", content_type="somethingelse") + + _, response = await app.asgi_client.get("/json") + assert response.headers.get("content-type") == "application/json" + + _, response = await app.asgi_client.get("/text") + assert response.headers.get("content-type") == "text/plain; charset=utf-8" + + _, response = await app.asgi_client.get("/custom") + assert response.headers.get("content-type") == "somethingelse"