Skip to content

Commit

Permalink
Add JSONResponse
Browse files Browse the repository at this point in the history
  • Loading branch information
sloria committed Oct 28, 2015
1 parent 86faf1b commit c95151d
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
21 changes: 20 additions & 1 deletion aiohttp/web_reqrep.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@
from .streams import EOF_MARKER


__all__ = ('ContentCoding', 'Request', 'StreamResponse', 'Response')
__all__ = (
'ContentCoding', 'Request', 'StreamResponse', 'Response', 'JSONResponse'
)


sentinel = object()
Expand Down Expand Up @@ -810,3 +812,20 @@ def write_eof(self):
if body is not None:
self.write(body)
yield from super().write_eof()


def json_dumps(data):
return json.dumps(data).encode('utf-8')


class JSONResponse(Response):
content_type = 'application/json'

def __init__(self, data, *, body=None, status=200,
reason=None, headers=None, content_type=None,
dumps=json_dumps):
self.data = data
body = dumps(self.data)
content_type = content_type or self.content_type
super().__init__(body=body, status=status, reason=reason,
content_type=content_type)
32 changes: 31 additions & 1 deletion tests/test_web_response.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import datetime
import json
import pytest
import re
from unittest import mock
from aiohttp import hdrs, signals
from aiohttp.multidict import CIMultiDict
from aiohttp.web import ContentCoding, Request, StreamResponse, Response
from aiohttp.web import (
ContentCoding, Request, StreamResponse, Response, JSONResponse
)
from aiohttp.protocol import HttpVersion, HttpVersion11, HttpVersion10
from aiohttp.protocol import RawRequestMessage

Expand Down Expand Up @@ -836,3 +839,30 @@ def test_text_with_empty_payload():
resp = Response(status=200)
assert resp.body is None
assert resp.text is None


class TestJSONResponse:

def test_data_attribute(self):
resp = JSONResponse('jaysawhn')
assert 'jaysawhn' == resp.data

def test_content_type_is_application_json_by_default(self):
resp = JSONResponse('')
assert 'application/json' == resp.content_type

def test_body_is_json_encoded(self):
resp = JSONResponse({'foo': 42})
assert json.dumps({'foo': 42}).encode('utf-8') == resp.body

def test_content_type_is_overrideable(self):
resp = JSONResponse({'foo': 42},
content_type='application/vnd.json+api')
assert 'application/vnd.json+api' == resp.content_type

def test_content_type_is_overrideable_as_class_var(self):
class MyJSONResponse(JSONResponse):
content_type = 'application/vnd.json+api'

resp = MyJSONResponse('jaysawhn')
assert 'application/vnd.json+api' == resp.content_type

0 comments on commit c95151d

Please sign in to comment.