Merge pull request #1654 from huge-success/asgi-content-type

Add content-type headers in response in ASGI mode
This commit is contained in:
7 2019-08-13 12:30:40 -07:00 committed by GitHub
commit 41862eca61
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 1 deletions

View File

@ -327,6 +327,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(
{

View File

@ -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"